您的位置:首页 > 编程语言 > C语言/C++

欢迎使用CSDN-markdown编辑器

2015-08-06 12:20 393 查看
[C++内存分配]的一篇好文章

重新了解了深拷贝和拷贝构造函数的用途!

#include<iostream>
using namespace std;

class Test
{
public:
int size;
int *p;
Test(int s)             //带参数的构造函数
{
size = s;
p = new int[size];
for (int i = 0; i < s; i++)
p[i] = i;
}
Test()                  //不带参数的构造函数
{
size = 0;
p = NULL;//size=0,分配内存有个卵用,之前写的是p = new int[size];
}
Test* clone(Test& t) //  这里不能直接用 Test t,否则这个 t是将t1复制一份出来,包括里面的*p,
//当退出clone时,会析构这个复制的t,但这个复制的t 与t1中的*p是指向同一个地方,此时,*p又会删除2次
{
Test *result = new Test(t.size);
result->size = t.size;
cout << result->size << " is size" << endl;

for (int i = 0; i < result->size; i++)
result->p[i] = t.p[i];
//result.p = t.p;
return result;
}
~Test()                    //析构函数
{
if(NULL!=p)
{
delete []p;
}           //这行注释掉程序就不会错
}
};

int main()
{
Test t1 = Test(10);
Test *t2 = t1.clone(t1);
int i;
for (i = 0; i != t2->size; i++)
{
t2->p[i] = 0;
}
cout << "it is over" << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 namespace class