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

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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: