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

13.14    使用合成的拷贝控制成员,则直接复制mysn的值,f(a), f(b), f(c)输出相同的结果。

 

13.15    使用自定义的拷贝构造函数生产新序号,会改变结果。但b=a, c=b,及三次调用f(),都运行了拷贝构造函数,每次都产生新的序号,因此f(a), f(b), f(c)的输出和a, b, c中的mysn值并不相同。

 

13.16    参数使用const numbered&会改变输出结果,此时b=a, c=b会调用拷贝构造函数,调用f()不会使用拷贝构造函数,而是直接输出参数的mysn值,因此f(a), f(b), f(c)的输出和a, b, c中的mysn值相同。

 

13.17    第一个测试代码,使用合成的拷贝构造函数:

#include <iostream>

using namespace::std;

class numbered {
public:
	numbered() {mysn = num++;}		//定义默认构造函数
	int mysn = 0;
private:
	static int num;
};

int numbered::num = 0;

void f(numbered s)
{
	cout << s.mysn << endl;
}

int main()
{
	numbered a, b = a, c = b;
	
	f(a);
	f(b);
	f(c);
	
	return 0;
}

运行输出 0 0 0

第二个代码定义了拷贝构造函数:

#include <iostream>

using namespace::std;

class numbered {
public:
	numbered() { mysn = num++; }		//定义默认构造函数
	numbered(const numbered &r) { mysn = num++; }		//拷贝构造函数
	int mysn = 0;
private:
	static int num;
};

int numbered::num = 0;

void f(numbered s)
{
	cout << s.mysn << endl;
}

int main()
{
	numbered a, b = a, c = b;
	
	f(a);
	f(b);
	f(c);
	
	return 0;
}

输出 3 4 5

第三段代码将f()的参数改为引用形式

#include <iostream>

using namespace::std;

class numbered {
public:
	numbered() { mysn = num++; }		//定义默认构造函数
	numbered(const numbered &r) { mysn = num++; }		//拷贝构造函数
	int mysn = 0;
private:
	static int num;
};

int numbered::num = 0;

void f(const numbered &s)	//参数为引用
{
	cout << s.mysn << endl;
}

int main()
{
	numbered a, b = a, c = b;
	
	f(a);
	f(b);
	f(c);
	
	return 0;
}

输出 0 1 2

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值