1、
#include <iostream>
using namespace std;
class stu
{
public:
int* a;
stu()
{
a = new int[3];
a[0] = 12;
a[1] = 134;
}
stu(const stu& b)//拷贝构造
{
this->a = new int[2];
this->a[0] = b.a[0];
this->a[1] = b.a[1];
//memcpy(this->a,b.a,sizeof(a)*2); 内存拷贝
}
~stu()
{
delete[] a;
}
};
int main()
{
{stu db;
cout << db.a[0] << " " << db.a[1] << endl;
stu db1(db);
cout << db1.a[0] << " " << db1.a[1] << endl;
system("pause");
}
return 0;
}
该博客探讨了C++中类的拷贝构造函数的实现,展示了如何正确地复制对象的成员变量,特别是动态分配的内存。示例代码中,作者创建了一个stu类,含有一个整型指针数组,并在拷贝构造函数中进行了内存的深拷贝,以避免浅拷贝导致的问题。在析构函数中,确保了动态内存的释放。
1906

被折叠的 条评论
为什么被折叠?



