#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");
}