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


你可能感兴趣的:(Effective C++学习系列一:拷贝构造函数与赋值符号的调用时机)