IDE Qt Creator 4.0.3
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:
Stock(); //默认构造函数
Stock(const std::string &co,long n=0,double pr=0.0); //构造函数
~Stock(); //析构函数
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;
//默认构造函数
Stock::Stock()
{
cout<<"Default constructor called\n";
company="no name";
shares=0;
share_val=0.0;
total_val=0.0;
}
//构造函数
Stock::Stock(const string &co, long n, double pr)
{
cout<<"Construcor using"<<co<<" called\n";
company=co;
if(n<0)
{
cout<<"Number of shares can't be negative;"
<<company<<"shares set to 0\n";
shares=0;
}
else
{
shares=n;
}
share_val=pr;
set_tot();
}
//析构函数
Stock::~Stock()
{
cout<<"bye,"<<company<<endl;
}
//对某个公司股票的首次购买
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<<"Using constructos to create new objects\n";
Stock stock1("NanoSmart",12,20.0);
stock1.show();
Stock stock2=Stock("Boffo Objects",2,2.0);
stock2.show();
cout<<"Assigning stock1 to stock2:\n";
stock2=stock1;
stock1.show();
stock2.show();
cout<<"Using a constructor to reset an object\n";
stock1=Stock("Nifty Foods",10,50.0); //临时对象
stock1.show();
cout<<"Done\n";
}
return 0;
}
运行结果如下