Stock.h
#ifndef STOCK_H_
#define STOCK_H_
#include<iostream>
class Stock
{
private:
char *company;
int shares;
double share_val;
double total_val;
void settot(){ total_val = shares*share_val; }
public:
Stock();
Stock(const char *ch, long n = 0, double pr = 0);
~Stock();
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
const Stock &top_val(const Stock &s)const;
friend std::ostream &operator<<(std::ostream &os, const Stock *s);
friend std::ostream &operator<<(std::ostream &os, Stock &s);
};
#endif
Stock.cpp
#include<iostream>
#include"Stock.h"
Stock::Stock()
{
company = new char[15];
strcpy_s(company,15,"no name");
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::~Stock()
{
delete[]company;
}
Stock::Stock(const char *ch, long n, double pr)
{
company = new char[strlen(ch)+1];
strcpy_s(company,strlen(ch)+1,ch);
if (n < 0)
{
std::cout << "Shares cannot be negtive .\n";
shares = 0;
}
else
shares = n;
share_val = pr;
settot();
}
void Stock::buy(long num, double price)
{
if (num < 0)
std::cout << "You cannot buy shares less than 0.\n";
else
shares += num;
share_val = price;
settot();
}
void Stock::sell(long num, double price)
{
if (num < 0)
std::cout << "You cannot sell shares less than 0.\n";
else if (num>shares)
std::cout << "You don't have enougn stocks .\n";
else
{
shares -= num;
share_val = price;
settot();
}
}
void Stock::update(double price)
{
share_val = price;
settot();
}
const Stock &Stock::top_val(const Stock &s)const
{
if (total_val > s.total_val)
return *this;
else
return s;
}
std::ostream &operator<<(std::ostream &os, const Stock *s)
{
os << "Company :" << s->company << " ;Shares :"<<s->shares<< '\n';
os << "Share price :" << s->share_val << '\n';
os << "Total worth :$"<<s->total_val << '\n';
return os;
}
std::ostream &operator<<(std::ostream &os, Stock &s)
{
os << "Company :" << s.company << " ;Shares :" << s.shares << '\n';
os << "Share price :" << s.share_val << '\n';
os << "Total worth :$" << s.total_val << '\n';
return os;
}
user.cpp
#include<iostream>
#include"Stock.h"
const int STKS = 4;
using namespace std;
int main()
{
Stock stock[STKS] =
{ Stock("Nanosmart", 12, 20.0),
Stock("Boffo Objects", 200, 2.0),
Stock("Monolithic Obliskes", 130, 3.25),
Stock("Fleep Enterprices", 60, 6.5) };
cout << "Stock holding :\n";
int st;
for (st = 0; st < STKS; st++)
cout << stock[st];
const Stock *top = &stock[0];
for (st = 1; st < STKS; st++)
top = &top->top_val(stock[st]);
cout << "Most valuable holding :\n";
cout << top;
return 0;
}