Effective C++学习系列一:拷贝构造函数与赋值符号的调用时机

#include<iostream>

using namespace std;

class Integer
{
public:
	int integer;

	Integer()
	{
		integer = 0;
		cout << "Default constructor called with this pointer " 
			<< static_cast<void*>(this) << std::endl;
	}
	Integer(int i) : integer(i)
	{
		cout << "Constructor called with this pointer "
			<< static_cast<void*>(this) << std::endl;
	}
	Integer(const Integer& Int)
	{
		cout << "Copy constructor with this pointer "
			<< static_cast<void*>(this) << std::endl;
		this->integer = Int.integer;
	}
	const Integer operator=(const Integer& rhs)
	{
		if (this == &rhs)
			return *this;
		this->integer = rhs.integer;
		cout << "Assignment operator with this pointer "
			<< static_cast<void*>(this) << std::endl;
		return *this;
	}
};

int main()
{
	Integer i1;
	Integer i2(6);
	Integer i3 = i2;  // equal to i3(i2), call i3's copy construstor but not the assignment operator
	i1 = i2; // call i1's assignment operator, and the temporary object's copy constructor for return.
	cout << "i1: " << static_cast<void*>(&i1) << endl;
	cout << "i2: " << static_cast<void*>(&i2) << endl;
	cout << "i3: " << static_cast<void*>(&i3) << endl;
	return 0;
}


输出:

Default constructor called with this pointer 00AAFCBC
Constructor called with this pointer 00AAFCB0
Copy constructor with this pointer 00AAFCA4
Assignment operator with this pointer 00AAFCBC
Copy constructor with this pointer 00AAFBD8
i1: 00AAFCBC
i2: 00AAFCB0
i3: 00AAFCA4


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值