2.39 类定义的最后要加上分号。
2.40
struct Sales_data {
string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
2.41 见2.42题
2.42 Sales_data.h头文件
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <iostream>
#include <string>
using namespace std;
struct Sales_data {
string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
#endif
输出两个Sales_data对象之和:
#include "Sales_data.h"
using namespace std;
int main()
{
Sales_data item1, item2;
double price = 0;
cin >> item1.bookNo >> item1.units_sold >> price;
item1.revenue = item1.units_sold * price;
cin >> item2.bookNo >> item2.units_sold >> price;
item2.revenue = item2.units_sold * price;
if (item1.bookNo == item2.bookNo) {
unsigned totalCnt = item1.units_sold + item2.units_sold;
double totalRevenue = item1.revenue + item2.revenue;
cout << item1.bookNo << " " << totalCnt << " " << totalRevenue << endl;
} else {
cerr << "Data must refer to the same ISBN" << endl;
return -1;
}
return 0;
}
用Sales_data重写1.6节程序
#include "Sales_data.h"
using namespace std;
int main()
{
Sales_data total;
double price = 0;
if (cin >> total.bookNo >> total.units_sold >> price) {
total.revenue = total.units_sold * price;
Sales_data trans;
while (cin >> trans.bookNo >> trans.units_sold >> price) {
trans.revenue = trans.units_sold * price;
if (total.bookNo == trans.bookNo) {
total.units_sold += trans.units_sold;
total.revenue += trans.revenue;
} else {
cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl;
total.bookNo = trans.bookNo;
total.units_sold = trans.units_sold;
total.revenue = trans.revenue;
}
}
cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl;
} else {
cerr << "No data?!" << endl;
return -1;
}
return 0;
}
本文主要介绍了C++ Primer第五版中2.6.1至2.6.3节的练习内容,包括类定义的结束分号、相关问题解答以及如何使用Sales_data类重写1.6节的程序,实现两个Sales_data对象的求和操作。

4671

被折叠的 条评论
为什么被折叠?



