C++ Primer(第5版) 练习 7.41
练习 7.41 使用委托构造函数重新编写你的Sales_data类,给每个构造函数体添加一条语句,令其一旦执行就打印一条消息。用各种可能的方式分别创建Sales_data对象,认真研究每次输出的信息直到你确实理解了委托构造函数的顺序。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
/*************************************************************************
> File Name: ex7.41.cpp
> Author:
> Mail:
> Created Time: Thu 22 Feb 2024 12:26:50 PM CST
************************************************************************/
#include<iostream>
using namespace std;
struct Sales_data{
Sales_data(const string &s, unsigned n, double p):
bookNo(s), units_sold(n), price(p), revenue(p * n) {cout<<"Three Parameters"<<endl;}
Sales_data(): Sales_data("", 0, 0) { cout<<"Default Parameters"<<endl; }
Sales_data(string s): Sales_data(s, 0, 0) { cout<<"Accept string Parameter"<<endl; }
Sales_data(istream &);
friend ostream &print(ostream&, const Sales_data&);
friend istream &read(istream&, Sales_data&);
string isbn() const;
Sales_data& combine(const Sales_data&);
double avg_price() const;
string bookNo;
unsigned units_sold = 0;
double price = 0.0;
double revenue = 0.0;
};
Sales_data::Sales_data(istream &in){
read(in, *this);
}
string Sales_data::isbn() const{
return this->bookNo;
}
Sales_data& Sales_data::combine(const Sales_data &rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
double Sales_data::avg_price() const{
if(units_sold){
return revenue / units_sold;
}
else{
return 0;
}
}
Sales_data add(const Sales_data &sd1, const Sales_data &sd2){
Sales_data t = sd1;
t.combine(sd2);
return t;
}
ostream &print(ostream &output, const Sales_data &sd){
output<<sd.bookNo<<" "<<sd.units_sold<<" "<<sd.price<<" "<<sd.revenue<<" "<<sd.avg_price()<<endl;
return output;
}
istream &read(istream &input, Sales_data &sd){
input>>sd.bookNo>>sd.units_sold>>sd.price;
sd.revenue = sd.price * sd.units_sold;
return input;
}
int main(){
Sales_data book1("0-201-78345-X", 1, 20.00);
Sales_data book2;
Sales_data book3("0-301-76459-Y");
return 0;
}