chapter12test3

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值