C++ Primer 7.1.2节练习

// 7.1.2节练习.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

///定义类
struct Sales_data {
    std::string isbn() const {
        return bookNo;
    };
    Sales_data& combine(const Sales_data &rhs);
    std::string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
};
////////练习7.2:向Sales_data这个类添加combine和isbn成员
////////定义combine类内函数
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
    units_sold = rhs.units_sold + units_sold;
    revenue += rhs.revenue;
    return *this;  

}
////////定义isbn类内函数


////////练习7.3:令7.1.1节的交易处理程序使用这些成员
int main()
{
    Sales_data total;//保存下一条交易记录的变量
                     //读入第一条交易记录,并确保有数据可以处理
    total.bookNo = "abcdefg";
    total.revenue = 0.2;
    total.units_sold = 10;
    if (total.bookNo != "") {
        Sales_data trans; //保存和的变量
                          //读入并处理剩余交易记录
        trans.bookNo = "abcdefg";
        trans.revenue = 0.2;
        trans.units_sold = 10;

        //如果我们仍在处理相同的书
        if (total.isbn() == trans.isbn())
            total.combine(trans);///使用类函数
        //更新总销售额
        else {
            //打印前一本书的结果
            std::cout << total.units_sold * total.revenue << std::endl;
            total.units_sold = trans.units_sold;
            //total现在表示下一本书的销售额 
        }
    }
    std::cout << total.units_sold * total.revenue << std::endl;
    //打印最后一本书的结果 
    if (total.isbn() == "") {
        //没有输入!警告读者
        std::cerr << "No data?" << std::endl;
        return -1; //表示失败 
    }
    return 0;
}

上面是练习7.2与练习7.3,较为容易

下面是练习7.4与7.5,编写一个Person类,令其用来表示人员的姓名和地址,并提供一组操作返回名字与地址;这些函数是否应该是const的。

是,对于调用其信息来说,应该选择const,可以支持更多的类型,这样就可以读取其成员而不可修改。

#include "stdafx.h"
#include <iostream>
using namespace std;

///练习7.4声明Person类


struct Person {
    string name;
    string address;
    ////练习7.5
    string getName() const { return name; }
    string getAddress() const { return address; }
};



int main()
{
    Person Gao;
    Gao.address = "愉快";
    Gao.name = "我啊";
    for (auto c : Gao.getAddress())
        cout << c;
    for (auto c : Gao.getName())
        cout << c;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Fengyuyang/p/9103771.html