拷贝构造函数形参规格

拷贝构造函数形参规格

拷贝构造函数的形参基本都写为常量引用。
#include <iostream>
using namespace std;

class A
{	
public:
	A(int data = 0) : m_data(data) {}
	~A() {}

	A(const A& other)
	{
		m_data= other.m_data;
	}
	void print()
	{
		cout << m_data<< endl;
	}
private:
	int m_data;
};

int main()
{
	A a(1);
	A b = a;	// call copy constructor (A::A(A&) or A::A(const A&))

	A c = 2;	// call constructor and copy constructor (A::A(const A&))
	A d = c;	// call copy constructor (A::A(A&) or A::A(const A&))

	const A e(3);	// const object
	A f = e;	// call copy constructor (A::A(const A&))

	return 0;
}
main函数第一条语句调用构造函数生成一个对象。A b = a; 语句调用拷贝构造函数来生成一个对象,这里的拷贝构造函数可以使用两种形式参数引用和常量引用。
A c = 2; 由于有参数为int的构造函数,所以右端会调用这个构造函数生成一个临时变量,然后调用拷贝构造函数,由于临时变量为常量,所以这里调用的拷贝构造函数的形参必须为常量引用。
A d = c; 与A b = a; 原理相同
A f = e; 由于const变量不能转换为非const变量,所以这里调用的构造函数必须为常量引用。

总之:拷贝构造函数的形式参数中的const,是为了使用const对象来构造新对象。而其中的&则不可或缺,否则就会出现拷贝构造函数调用的递归调用。对于形参的出错情况,编译器都会给出错误。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值