C++ Primer(第五版)7.1.4节练习

本文主要探讨了C++ Primer第五版中7.1.4节的练习,涉及如何添加构造函数、将构造函数移到类内部等关键知识点,旨在帮助读者深入理解C++构造函数的使用和管理。

7.11    添加构造函数

struct Sales_data {
	Sales_data()= default;
	Sales_data(const string &s): bookNo(s) { }
	Sales_data(const string &s, unsigned n, double p): 
				bookNo(s), units_sold(n), revenue(p) { }
	Sales_data(istream &);
	/* ... */
};

Sales_data::Sales_data(istream &is)
{
	read(is, *this);
}

使用构造函数:

#include <iostream>
#include "Sales_data.h"

using namespace std;

int main()
{
	Sales_data s1;
	print(cout, s1) << endl;
	
	Sales_data s2("book1");
	print(cout, s2) << endl;
	
	Sales_data s3("book2", 10, 5.5);
	print(cout, s3) << endl;
	
	Sales_data s4(cin);
	print(cout, s4) << endl;
	
	return 0;
}

7.12    将构造函数移到类内部:

struct Sales_data;

Sales_data add(const Sales_data &lhs, const Sales_data &rhs);
istream &read(istream &is, Sales_data &item);
ostream &print(ostream &os, const Sales_data &item);

struct Sales_data {
	/* ... */
	Sales_data(istream &is) { read(is, *this); }
	/* ... */
};

7.13    

#include "Sales_data.h"

using namespace std;

int main()
{
	Sales_data total;
	
	if (read(cin, total)) {
		total.revenue = total.units_sold * price;
		
		Sales_data trans;
		while (read(cin, trans)) {
			trans.revenue = trans.units_sold * price;
			if (total.isbn() == trans.isbn()) {
				total.combine(trans);
			} else {
				cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl;
				total = trans;
			}
		}
		cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl;
	} else {
		cerr << "No data?!" << endl;
		return -1;
	}
	
	return 0;
}

7.14   

struct Sales_data {
	/* ... */
	Sales_data(): bookNo(""), units_sold(0), revenue(0.0) { }
	/* ... */
};

7.15    

class Person {
public:
	Person() = default;
	Person(const string &name, const string &add): name(name), address(add) { }
	string getName() const { return name; }
	string getAddress() const { return address; }
private:
	string name;
	string address;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值