class CastC {
public:
int i;
int len;
int* p;
CastC() {
this->i=0;
this->len = 0;
this->p = NULL;
}
CastC(int i, int len) {
this->i = i;
this->len = len;
this->p = new int[len];
}
CastC(const CastC& c) {//深拷贝
this->i = c.i;
this->len = c.len;
this->p = new int[c.len];
for (int i = 0; i < len; i++) {
this->p[i] = c.p[i];
}
}
CastC& operator=(const CastC& c) {//重写=操作符
if (this->p != NULL) {
delete p;
p = NULL;
this->i = 0;
this->len = 0;
}
this->i = c.i;
this->len = c.len;
this->p = new int[c.len];
for (int i = 0; i < len; i++) {
this->p[i] = c.p[i];
}
return *this;
}
};
void testCopy() {
CastC p1(1, 10);
p1.p[1] = 10;
CastC p2;
p2 = p1;
p2 = p1;
cout << p2.p[1];
}
c++深拷贝和重载=
最新推荐文章于 2024-03-10 19:03:11 发布
本文介绍了C++中类的深拷贝和浅拷贝的概念,并展示了`CastC`类如何实现深拷贝构造函数和重载赋值运算符。在`testCopy`函数中,通过创建`CastC`对象并进行拷贝操作,展示了深拷贝和浅拷贝的区别,以及在内存管理中的应用。
摘要由CSDN通过智能技术生成