思维导图
完善剩余
#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()//析构函数
{
delete p;
cout << "Stu::析构函数,this = " << this << endl;
}
//深拷贝函数
Person(const Person& other) :age(other.age), p(new int(*(other.p)))
{
cout << "Stu::拷贝构造" << endl;
}
//拷贝赋值函数
Person& operator=(const Person& other)
{
if (this != &other) //防止自己给自己赋值
{
this->age = other.age;
*(this->p) = *(other.p); //深拷贝
}
cout << "Stu::拷贝赋值函数" << endl;
return *this; //返回自身引用
}
};
int main()
{
Person p1; //无参构造
Person p2(p1); //拷贝构造
cout << "&p1 = " << &p1 << endl;
cout << "&p2 = " << &p2 << endl;
Person p3; //无参构造
p3 = p2;
return 0;
}