C++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator= ,对属性进行值拷贝
  • 如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;


class Person {
public:
Person(int age) {
Age = new int(age);
}
~Person()
{
if (Age != NULL) {
delete Age;
Age = NULL;
}
}
Person &operator=(Person &p) {
if (Age != NULL) {
delete Age;
Age = NULL;
}
Age = new int(*p.Age);
return *this;
}
int* Age;
};
void test01() {
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
cout << "p1.age=" << *p1.Age << endl;
cout << "p2.age=" << *p2.Age << endl;
cout << "p3.age=" << *p3.Age << endl;
}

int main(){
test01();
return 0;
}