C++ primer plus第六版课后编程题答案12.3


 

Stock.cpp

#include <iostream>
using namespace std;
class Stock{
private:
	char *company;
	int shares;
	double share_val;
	double total_val;
	void set_tot(){total_val=shares*share_val;};
public:
	Stock(){
		company=new char[8];
		strcpy(company,"no name");
		shares=0;
		share_val=0.0;
		total_val=0.0;
	}
	Stock(const char *co,long n=0,double pr=0)
	{
		int len=strlen(co);
		company=new char[len+1];
		strcpy(company,co);
		if(n<0)
		{
			cout<<"Number of shares can't be negative;"
				<<company<<" shares set to 0"<<endl;
			shares=0;
		}
		else
			shares=n;
		share_val=pr;
		set_tot();
	}
	~Stock()
	{
		delete []company;
	}
	void buy(long num,double price)
	{
		if(num<0)
		{
			cout<<"Number of shares purchase can't be negative."
				<<" Transaction is aborted."<<endl;
		}
		else
		{
			shares+=num;
			share_val=price;
			set_tot();
		}
	}
	void sell(long num,double price)
	{
		if(num<0)
		{
			cout<<"Number of shares sold can't be negative."
				<<"Transaction  is  aborted."<<endl;
		}
		else if(num>shares)
		{
				cout<<"You can't sell more than you have!"
					<<"Transaction  is  aborted."<<endl;
		}
		else
		{
			shares-=num;
			share_val=price;
			set_tot();
		}
	}
	void update(double price)
	{
		share_val=price;
		set_tot();
	}
	const Stock &topval(const Stock &s)const
	{
		if(s.total_val>total_val)
			return s;
		else
			return *this;
	
	}

	friend ostream &operator<<(ostream &os,const Stock &s)
	{
		//ios_base::fmtflags orig=os.setf(ios_base::floatfield);//格式化语句,看不太懂
		ios_base::fmtflags orig=os.setf(ios_base::fixed,ios_base::floatfield);
		streamsize prec=os.precision(3);
		os<<"Company:"<<s.company
			<<"  Shares:"<<s.shares<<endl;
		os<<" Share Price:$"<<s.share_val;
		os.precision(2);
		os<<"    Total Worth:&"<<s.total_val<<endl;
		os.setf(orig,ios_base::floatfield);
		os.precision(prec);
		return os;
	}
};//倘若要被包含,这里必须要有;???
//是的,必须要,否则VS会报错,说是发现意外的文件尾

main123.cpp

#include <iostream>
#include "Stock.cpp"
using namespace std;
const int STKS=4;
void main123()
{
	Stock stocks[STKS]={
		Stock("NanoSmart",12,20.0),
		Stock("Boffo Object",200,2.0),
		Stock("Monolithic obelisk",130,3.25),
		Stock("Fleep Enterprises",60,6.5),
	};
	cout<<"Stock holdings"<<endl;
	int st;
	for(st=0;st<STKS;st++)
		cout<<stocks[st];
	const Stock *top=&stocks[0];
	for(st=1;st<STKS;st++)
		//top=&(top->topval(stocks[st]));//为何只能用&而不能用*
		top=&top->topval(stocks[st]);//top是一个指向对象的指针,
	//哦,我知道了,top的确是一个指针,因此才要&,你仔细想想,为什么呢?看我上一条语句的括号
	cout<<*top;       //cout<<top;top是一个指针,应该使用*top
	//&top->update(3.0);//怎么这一句就不行了呢?
	//return 0;
}

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注