P10.3 usestock0.cpp

stock.h

#ifndef STOCK_H
#define STOCK_H

#include <string>

class Stock  //类声明
{
private:
    std::string company;
    long shares;  //
    double share_val;
    double total_val;
    void set_tot(){total_val=share_val*shares;}
public:
    void acquire(const std::string &co,long n,double pr);  //获得股票
    void buy(long num,double price);  //买入股票
    void sell(long num,double price);  //卖出股票
    void update(double price);  //更新股票价格
    void show();  //显示关于所持股票的信息
};

#endif // STOCK_H

main.cpp

#include <iostream>
#include "stock.h"

using namespace std;
//对某个公司股票的首次购买
void Stock::acquire(const string &co, long n, double pr)
{
    company=co;
    if(n<0)
    {
        cout<<"Number of shares can't be negative;"
           <<company<<"shares set to 0.\n";
    }
    else
    {
        shares=n;
    }
    share_val=pr;
    set_tot();
}
//购买股票
void Stock::buy(long num, double price)
{
    if(num<0)
    {
        cout<<"Number of shares purchased can't be negative."
           <<"Transaction is aborted.\n";
    }
    else
    {
        shares+=num;
        share_val=price;
        set_tot();
    }
}
//减少持有的股票
void Stock::sell(long num, double price)
{
    if(num<0)
    {
        cout<<"Number of shares sold cna't be negative."
           <<"Transaction is aborted.\n";
    }
    else if(num>shares)
    {
        cout<<"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()
{
    ios_base::fmtflags orig=
            cout.setf(ios_base::fixed,ios_base::floatfield);
    std::streamsize prec=cout.precision(3);
    cout<<"Company:"<<company
       <<" Shares:"<<shares<<'\n';
    cout<<" Shares Price:$"<<share_val;
       cout.precision(3);
     cout<<" Total Worth:$"<<total_val<<'\n';

     //show()应重置格式信息,使其恢复到自己被调用前的状态
     cout.setf(orig,ios_base::floatfield);
     cout.precision(prec);
}
int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;
    Stock fluffy_the_cat;
    fluffy_the_cat.acquire("NanoSmart",20,12.50);
    fluffy_the_cat.show();
    fluffy_the_cat.buy(15,18.125);
    fluffy_the_cat.show();
    fluffy_the_cat.sell(400,20.00);
    fluffy_the_cat.show();
    fluffy_the_cat.buy(300000,40.125);
    fluffy_the_cat.show();
    fluffy_the_cat.sell(300000,0.125);
    fluffy_the_cat.show();
    return 0;
}

运行结果如下

posted @ 2018-09-30 20:22  尚修能的技术博客  阅读(215)  评论(0编辑  收藏  举报