2、
#include <iostream>
using namespace std;
class Person
{
private:
int age;
int *p;
public:
//无参构造
Person():p(new int(89))
{
age = 18;
}
//有参构造
Person (int age,int num)
{
this->age = age;
this-> p = new int(num);
}
//拷贝构造函数(深度拷贝)
Person(Person &other)
{
age = other.age;
*p = *(other.p);
}
//拷贝赋值函数
Person &operator=(Person &other)
{
if(this != &other)
{
age = other.age;
*p = *(other.p);
}
return *this;
}
void show()
{
cout << "age = "<< age <<endl;
cout << "address = " << &p << endl;
}
//析构函数
~Person()
{
delete p;
p = nullptr;
cout << "析构函数调用" << endl;
}
};
int main()
{
Person p1 (20,100);
cout << "p1 :";
p1.show();
cout <<endl;
Person p2 = p1;
cout << "拷贝函数p2 :";
p2.show();
cout <<endl;
Person p3;
p1 = p3;
cout << "拷贝赋值函数 : ";
p1.show();
cout <<endl;
return 0;
}
运行效果如下