7.1定义抽象数据类型
Sales_data类
头文件
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 class Sales_data 5 { 6 friend Sales_data add(const Sales_data &, const Sales_data &); 7 friend istream &read(istream &, Sales_data &); 8 friend ostream &print(ostream &, const Sales_data &); 9 10 public: 11 Sales_data() = default; //构造函数 12 Sales_data(const string &s) :bookNo(s) {} 13 Sales_data(const string &s, unsigned n, double p) :bookNo(s), units_sold(n), revenue(p*n) {} 14 Sales_data(istream &); 15 16 17 string isbn() const { return bookNo; } //相当于 string isbn () const { return this -> bookN0 } 18 Sales_data &combine(const Sales_data &); 19 20 private: 21 double avg_price() const; 22 string bookNo; //书ISBN编号 23 unsigned units_sold = 0; //书籍销量 24 double revenue = 0.0; //书籍销售收入 25 }; 26 27 Sales_data add(const Sales_data &lhs, const Sales_data &rhs) 28 { 29 Sales_data sum = lhs; 30 sum.combine(rhs); 31 return sum; 32 } 33 istream &read(istream &is, Sales_data &item) 34 { 35 double price = 0; 36 is >> item.bookNo >> item.units_sold >> price; 37 item.revenue = item.units_sold * price; 38 return is; 39 } 40 41 ostream &print(ostream &os, const Sales_data &item) 42 { 43 os << item.isbn() << " " << item.units_sold << " " 44 << item.revenue << " " << item.avg_price(); 45 return os; 46 } 47 48 Sales_data::Sales_data(istream &is) 49 { 50 read(is, *this); 51 } 52 Sales_data& Sales_data::combine(const Sales_data &rhs) 53 { 54 units_sold += rhs.units_sold; 55 revenue += rhs.revenue; 56 return *this; 57 } 58 59 double Sales_data::avg_price() const 60 { 61 if (units_sold) 62 return revenue / units_sold; 63 else 64 return 0; 65 }
源文件
1 #include<iostream> 2 #include"Sales_data.h" 3 4 using namespace std; 5 int main() 6 { 7 Sales_data total; 8 if (read(cin, total)) 9 { 10 Sales_data trans; 11 while (read(cin, trans)) 12 { 13 if (total.isbn() == trans.isbn()) 14 total.combine(trans); 15 else 16 { 17 print(cout, total) << endl; 18 total = trans; 19 } 20 } 21 print(cout, total) << endl; 22 } 23 else 24 { 25 cerr << "NO data?" << endl; 26 } 27 }
构造函数:每个类都分别定义了它的对象被初始化方式,类通过一个或几个特殊成员函数来控制其对象的初始化过程,这些函数叫做构造函数。【注意】1. 构造函数的名字和类相同 2.构造函数没有返回类型。
7.2类的其他特性