C++编程难题,急求解答,谢谢!
1.下面是股票类的声明文件,请你补充该类的实现,并使用应用程序进行测试。
//头文件stock.h
#ifndef STOCK_H
#define STOCK_H
class Stock
{
private:
char *co_name;
//公司名称
int shares;
//持股数
double share_val;//单股价格
double total_val;//股值=持股数*单股价格
public:
Stock();
//默认构造函数
Stock(const char *co,int sh, double sh_val);
~Stock();
void buy(int num,double price);//买入股票
void sell(int num,double price);//卖出股票
void update(double price);
//更改股价
void show() const;
//输出公司股票信息
const Stock& topval(const Stock &s) const;//比较两种股票的股值,返回股值大的股票公司
};
#endif
答案:#include <iostream>
using namespace std;
class Stock
{
private:
char *co_name;
//公司名称
int shares;
//持股数
double share_val;//单股价格
double total_val;//股值=持股数*单股价格
public:
Stock();
//默认构造函数
Stock(char *co,int sh, double sh_val);
~Stock();
void buy(int num,double price);//买入股票
void sell(int num,double price);//卖出股票
void update(double price);
//更改股价
void show() const;
//输出公司股票信息
const Stock& topval(const Stock &s) const;//比较两种股票的股值,返回股值大的股票公司
};
Stock::Stock(){}
Stock::Stock(char *co,int sh, double sh_val)
{
co_name=co;
shares=sh;
share_val=sh_val;
total_val=shares*share_val;
}
Stock::~ Stock(){}
void Stock::buy(int num,double price)
{
shares=num;
share_val=price;
total_val=shares*share_val;
}
void Stock::sell(int num,double price)
{
shares=shares-num;
share_val=price;
total_val=shares*share_val;
}
void Stock::update(double price)
{
share_val=price;
total_val=shares*share_val;
}
void Stock::show() const
{
cout<<"\
The company name of the stock is: "<<co_name<<endl;
cout<<"The number of shares purchased is: "<<shares<<endl;
cout<<"The price of single stock is: "<<share_val<<endl;
cout<<"The total price os the stock is: "<<total_val<<endl<<endl;
}
const Stock& Stock:: topval(const Stock &s) const
{
Stock a;
if(total_val>s.total_val)
{
a.co_name=co_name;
a.shares=shares;
a.share_val=share_val;
a.total_val=total_val;
return a;
}
else
return s;
}
int main()
{
Stock stock[3]={Stock("zhongyidong",0,0),Stock("zhongshihua",0,0)};
char s[2][50]={"zhongyidong","zhongshihua"},c;
int num,del;
double price;
for(int i=0;i<2;i++)
{
cout<<"The number of shares purchased in "<<s[i]<<": ";
cin>>num;
cout<<"The price of single stock: ";
cin>>price;
stock[i].buy(num,price);
cout<<"Sell the stock? "<<"y/n?"<<endl;
cin>>c;
if(c=='y')
{
cout<<"Number of shares to be sold: ";
cin>>num;
cout<<"Price of shares to be sold: ";
cin>>price;
stock[i].sell(num,price);
}
cout<<"Update the price of stock? "<<"y/n?"<<endl;
cin>>c;
if(c=='y')
{
cout<<"Price of the stock: ";
cin>>price;
stock[i].update(price);
}
}
cout<<"\
The largest companies in stock value is:\
";
stock[2]=stock[0].topval(stock[1]);
stock[2].show();
return 0;
}在说明里阿良
上一个:c++ 类库中list中的函数有哪些
下一个:学EE可以只学C++而不学C语言吗?