#include<iostream>
using namespace std;
#include <string>
#include <ostream>
class person {
public:
int* m_age;
person(int age) {
//将年龄数据开辟到堆区
m_age = new int(age);
//用m_age接收传来的age 为什么要用指针?
}
person& operator=(person &p) {//这里的意思是连续引用
if (m_age!=NULL) {
delete m_age;
m_age = NULL;
}
//编译器提供的代码是浅拷贝
//m_age=p.m_age;
//我们修改提供深拷贝 解决浅拷贝的问题
m_age = new int(*p.m_age);
//传进来的是person类型的 所以有p.m_age
//把定义的m_age开辟到堆区
//返回自身
return *this;
}
~person()
{
if (m_age!=NULL) {
delete m_age;
m_age = NULL;
}
}
};
void test01()
{
person p1(18);
person p2(20);
person p3(30);
p3 = p2 = p1;
cout << "p1的年龄为:" << *p1.m_age << endl;//用*是解引用
cout << "p2的年龄为:" << *p2.m_age << endl;
cout << "p3的年龄为:" << *p3.m_age << endl;
}
int main() {
test01();
system("pause");
return 0;
}
c++编译器至少给一个类添加4个函数
1. 默认构造函数(无参,函数体为空)
2. 默认析构函数(无参,函数体为空)
3. 默认拷贝构造函数,对属性进行值拷贝
4. 赋值运算符 operator=, 对属性进行值拷贝
用Person接收重构的赋值运算符