拷贝构造的创建与作用
#include<iostream>
using namespace std;
class ctext
{
public:
int b;
ctext()
{
b = 10;
}
ctext(const ctext& a)// 拷贝构造函数时调用的构造函数
{
this->b = a.b; // 拷贝构造默认的函数,浅拷贝
}
};
int main()
{
ctext text;
ctext text2(text); // 拷贝构造第一种写法
ctext text3 = text;// 拷贝构造第二种写法
ctext text4 = ctext(text);// 拷贝构造第三种写法
ctext *text5 = new ctext(text);// 拷贝构造第四种写法
cout << text.b<< " " << text2.b << endl;
system("pause");
return 0;
}
深拷贝
浅拷贝时 ,两个指针(只有指针变量会出现这种情况)变量指向的是同一块内存,内存释放的时候,容易将共同的内存一同释放,导致报错,进而我们需要深拷贝
#include<iostream>
using namespace std;
class ctext
{
public:
int *b;
ctext()
{
b = new int[2];
b[0] = 1;
b[1] = 2;
}
ctext(const ctext& a)// 拷贝构造函数时调用的构造函数
{
// 需要深拷贝的时候 需要申请独立空间
this->b = new int[2]; // 最好和上面一样,因为是复制过来的
this->b[0] = a.b[0];
this->b[1] = a.b[1];
memcpy(this->b,a.b,8); // 内存复制(新地址,源地址,字节个数(四个元素,8个字节))
}
~ctext()
{
delete[] b; // 析构函数默认的释放空间
}
};
int main()
{
ctext text;
cout << text.b[0] << " " << text.b[1] << endl;
ctext text1 = text;
cout << text1.b[0] << " " << text1.b[1] << endl;
system("pause");
return 0;
}
输出结果:
1 2
1 2