思维导图
拷贝复制函数
#include <iostream>
using namespace std;
class Person
{
string name;
int age;
public:
int *p;
Person():p(new int){}
Person(string name,int age):name(name),age(age),p(new int(10))
{cout << "Person的有参构造" << endl;}
void show()
{
cout << "name = " << name << " age = " << age << endl;
cout << "指针成员:" << p << "\t" << *p << endl;
}
///拷贝构造函数仍然是申请空间的,所以指针成员直接指向堆区的空间
Person(const Person &other):p(new int(*(other.p)))
{
this->name = other.name;
this->age = other.age;
cout << "Person的拷贝构造函数" << endl;
}
~Person()
{
cout << p << endl;
delete p;
}
//拷贝赋值函数没有初始化列表,返回自身的引用
Person &operator=(const Person &other)
{
//如果传过来的就是类对象本身,不执行赋值操作
if(&other!=this)
{
this->name = other.name;
this->age = other.age;
*(this->p) = *(other.p); //自己实现的深拷贝赋值
cout << "Person的拷贝赋值函数" << endl;
}
return *this; //通过this指针返回自身的引用
}
};
//fun函数的参数和返回值的位置都会调用拷贝构造函数
Person fun(Person p)
{
return p;
}
int main()
{
Person p1("zhangsan",12);
p1.show();
Person p2;
p2 = p1;
p2.show();
cout << *(p2.p) << endl;
return 0;
}