#include <iostream>
//先创建后析构
using namespace std;
class Name {
private:
char *pName;
int size;
public:
Name(const char *pname) {
size = strlen(pname);
pName = (char *)malloc(size + 1);
strcpy(pName, pname);
}
Name(Name &obj) {
//用obj初始化自己
pName = (char *)malloc(obj.size + 1);
strcpy(pName, obj.pName);
size = obj.size;
}
~Name() {
cout << "开始析构..." << endl;
if (pName != NULL) {
free(pName);
pName = NULL;
size = 0;
}
}
void operator=(Name &obj3) {
cout << "测试" << endl;
if (pName != NULL) { //如果这个if语句没有写,那么就会发生内存泄漏的事情,因为在进行operator=运算符重载时,n2 = obj2;//=号操作n2调用运算符重载,此时,n2的语句进行pName = (char *)malloc(obj.size + 1);内存分配时,原来n2初始化时pName所指的空间将会泄漏,找不到,所以要使用这个if语句
free(pName);
pName = NULL;
size = 0;
}
pName = (char *)malloc(sizeof(obj3.size + 1));
strcpy(pName, obj3.pName);
size = obj3.size;
}
};
void playObj() {
Name obj("obj1...");
Name n2 = obj;//创建并初始化
Name obj2("obj2...");
n2 = obj2;//=号操作
cout << "业务操作..." << endl;
}
int main() {
playObj();
system("pause");
return 0;
}