C++复制构造函数与等号重载

本文考虑的深复制

#include
using namespace std;

class C
{
private:
	int * pa;
	int b;
public:
	C(int a = 0, int b = 0)
	{
		pa = new int(a);
		this->b = b;
	}
	void print()
	{
		cout << "pa:" << pa << ";*pa:" << *pa << ";b:" << b << endl;
	}
	C(const C &c)//复制构造函数
	{
		this->b = c.b;
		if (pa)
			*(this->pa) = *(c.pa);
		else
			this->pa = new int(*(c.pa));
	}
	//返回值如果为空的话,可以满足c1 = c2的等号重载,但是满足不了c1 = c2 = c3的连等
	//因此使返回值为C&,可以使c2 = c3等式返回一个c2的引用,再赋值给c1.
	C& operator = (const C &c)
	{
		this->b = c.b;
		if (pa)
			*(this->pa) = *(c.pa);
		else
			this->pa = new int(*(c.pa));
		return *this;
	}
	~C()
	{
		delete pa;
	}
};

int main()
{
	C c1(2,3);
	c1.print();
	C c2(c1);
	c2.print();
	C c3 = c1;//若等号重载函数返回值为void,也会正常运行
	c3.print();
	C c4, c5;
	c4 = c5 = c1;//若等号重载函数返回值为void ,会报错
	c4.print();
	c5.print();

	system("pause");
	return 0;
}

运行结果:
C++复制构造函数与等号重载_第1张图片

你可能感兴趣的:(C++)