欢迎使用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; }
相关文章推荐
- Android Native 绘图方法
- Flex Namespace的用法
- C#中struct和class的区别详解
- Lua和C语言的交互详解
- VBS ArrayList Class vbs中的数组类
- 大家看了就明白了css样式中类class与标识id选择符的区别小结
- 关于C语言中参数的传值问题
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言内存对齐实例详解
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- 探讨C语言的那些小秘密之断言
- C语言实现BMP转换JPG的方法
- 深入探讨C语言中局部变量与全局变量在内存中的存放位置
- C语言查找数组里数字重复次数的方法
- C语言泛型编程实例教程
- C语言中使用lex统计文本文件字符数
- C语言进制转换代码分享
- 基于C语言fflush()函数的使用详解