c++编译器至少给一个类添加四个函数:
- 构造函数
- 析构函数
- 拷贝构造函数,对属性进行值拷贝;
- 赋值运算符,对属性进行值拷贝;
#include<iostream> using namespace std; class Person { public: Person(int age) { m_Age = new int(age); } int* m_Age; ~Person() { if (m_Age != NULL) { delete m_Age; m_Age = NULL; } } //这里需要使用引用,如果不用相当于利用拷贝函数新建了个对象 Person& operator=(Person& p) { //应该先判断是否有属性在堆区,如果有,则先释放干净,然后再进行深拷贝 if (m_Age != NULL) { delete m_Age; m_Age = NULL; } m_Age = new int(*p.m_Age); return *this; } }; void test() { Person p1(18); Person p2(20); Person p3(22); p3 = p2 = p1;//赋值操作 cout << "p1的年龄是:" << *p1.m_Age << endl; cout << "p2的年龄是:" << *p2.m_Age << endl; cout << "p3的年龄是:" << *p3.m_Age << endl; } int main() { test(); system("pause"); return 0; }
输出: