c++中拷贝构造函数

#include"Head.h"

class CStu
{
public:
	CStu()
	{

	}
	CStu(const CStu&)
	{

	}
};

int main()
{
	CStu stu1;
	/*以下4种会调用拷贝构造函数
	CStu stNew(stu1);
	CStu stNew = stu1;
	CStu stNew = CStu(stu1);
	CStu *stNew = new CStu(stu1);*/
	
	/*以下这样不会走拷贝构造函数,因为空间一开始就申请好了
	CStu stu2;
	stu1 = stu2;*/
	system("pause");
	return 0;
}

//注意点,浅拷贝,有指针成员时

#include"Head.h"

class CStu
{
public:
	int *a;
	CStu()
	{
		a = new int[2];
		a[0] = 12;
		a[1] = 15;
	}
		~CStu()
	{
		delete[] a;
	}
};
};

int main()
{
	CStu stu1;
	cout << stu1.a[0] << "\n" << stu1.a[1] << endl;

	CStu stu2 = stu1;//当类中有指针变量时,由于第一次创建对象时delete了a,再进行拷贝后,又一次删除a的地址,造成删除
//空地址,引起错误
	cout << stu2.a[0] << "\n" << stu2.a[1] << endl;

	system("pause");
	return 0;
}

解决办法是进行深拷贝,重写构造函数,申请空间

#include"Head.h"

class CStu
{
public:
	int *a;
	CStu()
	{
		a = new int[2];
		a[0] = 12;
		a[1] = 15;
	}
	~CStu()
	{
		delete[] a;
	}
	CStu(const CStu& b)
	{
		this->a = new int[2];    //重新申请空间,避免delete错误
		//a[0] = b.a[0];
		//a[1] = b.a[1];
		memcpy(this->a, b.a, 8);
	}
};

int main()
{
	CStu stu1;
	cout << stu1.a[0] << "\n" << stu1.a[1] << endl;

	CStu stu2 = stu1;								
	cout << stu2.a[0] << "\n" << stu2.a[1] << endl;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/piyixia/article/details/89042061