#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class PerSon
{
public:
int p_age;
char *p_name;
public:
PerSon(char* v_name,int v_age)
{
this->p_age = v_age;
// 构造名字
this->p_name = new char[strlen(v_name)+1];
strcpy(this->p_name, v_name);
cout<<"赋值构造函数"<<endl;
}
PerSon(const PerSon &v_person)
{
this->p_age = v_person.p_age;
this->p_name = new char[strlen(v_person.p_name)+1];
strcpy(this->p_name, v_person.p_name);
cout<<"拷贝构造函数"<<endl;
};
PerSon& operator=(const PerSon &v_person)
{
if (this->p_name != NULL)
{
delete[] this->p_name;
this->p_name = NULL;
}
this->p_age = v_person.p_age;
this->p_name = new char[strlen(v_person.p_name)+1];
strcpy(this->p_name,v_person.p_name);
cout<<"赋值运算符重载"<<endl;
return *this;
}
~PerSon()
{
if (this->p_name != NULL)
{
cout<<"进来吗"<<endl;
delete[] this->p_name;
this->p_name = NULL;
}
cout<<"析构函数"<<endl;
};
};
void test_01(void)
{
PerSon p1("cczhai",27);
PerSon p2 ("xuejing",30);
PerSon p3 = p2; // 拷贝构造函数
p3 = p2 = p1; // 运算符重载
cout<<"p1的名字为"<<p1.p_name<<" "<<"p1的年龄为"<<p1.p_age<<endl;
cout<<"p2的名字为"<<p2.p_name<<" "<<"p2的年龄为"<<p2.p_age<<endl;
cout<<"p3的名字为"<<p3.p_name<<" "<<"p3的年龄为"<<p3.p_age<<endl;
}
int main()
{
test_01();
system("pause");
return EXIT_SUCCESS;
}
运行结果: