chapter 2 自定义数据类型

2018-03-16

2.39 编译下面的程序观察并运行结果,注意,如果忘记写类定义体后面的分号会发生什么情况?记录下相关信息,以后可能会用。

 1 #include <iostream>
 2 
 3 int main()
 4 {
 5     int a = 3, b = 4;
 6     decltype(a) c = a; // c = 3,int型  
 7     std::cout << "c = " << c << " " << "a = " << a << std::endl; 
 8     decltype(a = b) d = a; // d = 3 int型 
 9     std::cout << "d = " << d << " " << "a = " << a << std::endl;
10     return 0;
11 
12 }

有error呗...还能怎样

 

2.40 根据自己的理解,写出Sales_data类,最好与书中的例子有所区别。

struct Sales_data{
    string name;
    unsigned bookNo;
    int is_sold = 0;
};

 

2.41 使用Sales_data重写1.51节、1.5.2节和1.6节的练习。眼下先把Sales_data类的定义和main函数放在同一个文件里

2.42 重写一个Sales_data.h头文件

emmm...我懒得重新写了,书上代码照着实现了一遍

1 #ifndef SALES_DATA_H    //当且仅当变量未定义时为真, #ifdef 当且仅当已定义时为真
2 #define SALES_DATA_H    //把其设为预处理变量
3 #include<string>
4 struct Sales_data {
5     std::string bookNo;
6     unsigned units_sold = 0;
7     double revenue = 0;
8 };
9 #endif      //遇到就结束
 1 #include<iostream>
 2 #include<string.h>
 3 #include "Sales_data.h"
 4 using namespace std;
 5 int main()
 6 {
 7     Sales_data data1, data2;
 8     double price = 0;   //书的单价,用于计算销售收入
 9 
10     //读入两笔交易
11     cin >> data1.bookNo >> data1.units_sold >> price;
12     data1.revenue = data1.units_sold * price;
13     cin >> data2.bookNo >> data2.units_sold >> price;
14     data2.revenue = data2.units_sold * price;
15 
16     if(data1.bookNo == data2.bookNo){
17         unsigned totalCnt = data1.units_sold + data2.units_sold;
18         double totalRevenue = data1.revenue + data2.revenue;
19         //输出
20         cout << data1.bookNo << " " << totalCnt << " " << totalRevenue << " ";
21         if(totalCnt != 0)
22             cout << totalRevenue / totalCnt << endl;
23         else
24             cout << "(no sales)" << endl;
25         return 0;
26     }
27     else{
28         cerr << "Data must refer to the same ISBN" << endl;
29         return -1;
30     }
31     return 0;
32 }

 

posted @ 2018-03-16 19:42  抹茶奶绿不加冰  阅读(184)  评论(0编辑  收藏  举报