C++拷贝构造函数的调用时机,如没有重载等号操作符,需重写使用深拷贝
2016-05-10 18:25
441 查看
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; /**拷贝构造函数 调用时机:(以下会调用copy) Test t1; Test t2=t1;//如果没有重载=操作符, Test t1(t2); void function(t1);//t1实参初始化形参 ,形参是一个元素 Test function(){ //函数的返回值是一个元素时 返回的是一个匿名对象 return t1; } */ class Test { public: Test() { a = 10; p = (char*)malloc(sizeof(char)*100); strcpy(p,"helloword!"); cout << "start" << endl; } void print() { cout << a << endl; cout << p << endl; } Test(const Test& ogj){//复写copy构造函数 使用深copy this->p = (char*)malloc(100); strcpy(this->p,ogj.p); this->a = ogj.a; cout << "copy" << endl; } Test(int a,char *p) { this->a = a; this->p = (char*)malloc(sizeof(char) * 100); strcpy(this->p, p); } ~Test() { if(p!=NULL){ free(p); } cout << "end" << endl; } private : int a; char *p; }; void function() { char* a = "hello"; Test t3(12,a); Test t4 = t3; t4.print(); } void main() { function(); system("pause"); }
相关文章推荐
- C语言将16进制的数转换为字符串的方法
- C++第五次实验(数组分离)
- c++ 内存分配过程(通过汇编,寄存器和Memory分析)
- C++ 无锁队列 ABA <1>
- C++<typeinfo>之typeid
- c++第五次实验-字符串
- c++作业5
- c++作业5
- c++第五次作业
- C++对象模型
- C++作业5
- 位操作相关资料汇总
- C++ 正则获取url中参数
- 【c语言】最小值与第一个值互换位置,最大值与最后一个互换位置
- c++第五次实验——数组分离
- Write Your software base on plugin(C/C++ ABI)
- C++ 字典遍历
- 如何利用C语言实现确定范围及不重复的随机数
- C++第五次实验
- C语言中变量存储类型有哪些?