-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock1.cpp
82 lines (75 loc) · 1.67 KB
/
stock1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// stock1.cpp --Stock class implementation with constructors, destructor added
#include <iostream>
#include <cstring>
#include "stock1.h"
// construction defintion
Stock::Stock() // default constructor
{
std::cout << "Default constructor called\n";
std::strcpy(company, "no name"); // different mothod to assign string
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char * co, int n, double pr)
{
std::cout << "Constructor using " << co << " called\n";
std::strncpy(company, co, 29); // different mothod to assign string
company[29] = '\0';
if (n < 0) {
std::cerr << "Number of shares can't be negative:"
<< company << " shares set to 0.\n";
shares = 0;
} else {
shares = n;
}
share_val = pr;
set_tot();
}
// destructor defition
Stock::~Stock()
{
std::cout << "Bye. " << company << "!\n";
}
// other methods
void Stock::buy(int num, double price)
{
if (num < 0)
{
std::cerr << "Number of shares purchased can't be negative. "
<< "Transaction is aborted.\n";
} else {
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(int num, double price)
{
using std::cerr;
if (num < 0) {
cerr << "Number of shares sold cannot be negative. "
<< "Transaction is aborted.\n";
} else if (num > shares) {
cerr << "You can't sell more than you have! "
<< "Transaction is aborted.\n";
} else {
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()
{
using std::cout;
using std::endl;
cout << "Company: " << company
<< " Shares: " << shares << endl
<< " Shares Price: $" << share_val
<< " Total Worth: $" << total_val << endl;
}