create exercise7_1.cpp, update common_bugs.md
This commit is contained in:
6
c++ note/chp7/chp7answers.md
Normal file
6
c++ note/chp7/chp7answers.md
Normal file
@@ -0,0 +1,6 @@
|
||||
Solutions to Exercises in Chapter Seven
|
||||
=======================================
|
||||
|
||||
> Exercise 7.1: Write a version of the transaction-processing program from §1.6 (p. 24) using the Sales_data class you defined for the exercises in §2.6.1 (p. 72).
|
||||
|
||||
[exercise7_1.cpp](exercise7_1.cpp)
|
||||
@@ -0,0 +1,56 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
struct Sales_data{
|
||||
string bookNo;
|
||||
unsigned units_sold = 0;
|
||||
double revenue = 0.0;
|
||||
|
||||
string isbn() const { return bookNo; }
|
||||
void combine(Sales_data const &data){
|
||||
units_sold += data.units_sold;
|
||||
revenue += data.revenue;
|
||||
}
|
||||
};
|
||||
|
||||
void add(Sales_data one, Sales_data two){
|
||||
one.combine(two);
|
||||
}
|
||||
|
||||
istream& read(istream &is, Sales_data &data){
|
||||
is >> data.bookNo;
|
||||
is >> data.units_sold;
|
||||
is >> data.revenue;
|
||||
return is;
|
||||
}
|
||||
|
||||
ostream& print(ostream &os, Sales_data const data){
|
||||
os << "book number: " << data.bookNo << endl;
|
||||
os << "units sold: " << data.units_sold << endl;
|
||||
os << "total revenue: " << data.revenue << endl;
|
||||
return os;
|
||||
}
|
||||
|
||||
int main(){
|
||||
Sales_data total; // variable to hold the running sum
|
||||
if (read(cin, total)) { // read the first transaction
|
||||
Sales_data trans; // variable to hold data for the next transaction
|
||||
while (read(cin, trans)) { // read the remaining transactions
|
||||
if (total.isbn() == trans.isbn()) // check the isbns
|
||||
total.combine(trans); // update the running total
|
||||
else {
|
||||
print(cout, total) << endl; // print the results
|
||||
total = trans; // process the next book
|
||||
}
|
||||
}
|
||||
print(cout, total) << endl; // print the last transaction
|
||||
}
|
||||
else { // there was no input
|
||||
cerr << "No data?!" << endl; // notify the user
|
||||
}
|
||||
|
||||
system("pause");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,4 +5,9 @@ Some Common Bugs
|
||||
|
||||
> 在调用了构造函数,进行了必要的初始化,之后的操作却出现了空指针?
|
||||
|
||||
因为我嵌套调用了构造函数。在构造函数中调用其他构造函数,只会产生一个匿名的对象,并不会帮助你初始化当前的对象。
|
||||
因为我嵌套调用了构造函数。在构造函数中调用其他构造函数,只会产生一个匿名的对象,并不会帮助你初始化当前的对象。
|
||||
|
||||
> 写了一个`read`函数,接受一个`istream`以及一个对象作为参数,即`read(istream is, myClass object)`。在函数体中利用输入流将数据读入对象中,并返回该`istream`作为进一步的判断或者使用。结果`object`没有得到赋值?!
|
||||
|
||||
|
||||
因为我是个傻逼。传入的`object`肯定要是引用啊。
|
||||
Reference in New Issue
Block a user