运算符重载(赋值运算符)

赋值运算符重载

  • c++ 编译器至少给一个类添加四个函数

    (1)默认构造函数(无参,函数体为空)

    (2)默认析构函数(无参,函数体为空)

    (3)默认拷贝构造函数,对属性进行值拷贝

    (4)赋值运算符 operator= ,对属性进行值拷贝

  • 如果类中有属性指向堆区,做赋值操作也会出现深浅拷贝问题

  • 在c++中为了实现连等,所以函数返回值为自身,并且可以提高效率,减少临时对象的开销。

示例:c++中内置连等,其运算结果为 a = 2 b = 1 c = 2,显然在执行完括号内赋值后返回了 a 本身。

1
2
3
4
5
int a = 0;
int b = 1;
int c = 2;
(a = b) = c;
cout << a << " " << b << " " << c << endl;

重载实现代码:

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
#include<iostream>
using namespace std;
class Person {
public:
int *m_age;
Person(int age){
m_age = new int(age);
}
~Person()
{
if (this->m_age != NULL) {
delete m_age;
m_age = NULL;
}
}
Person& operator=(Person& p) {
if (this->m_age != NULL) {
delete m_age;
m_age = NULL;
}
//深拷贝
m_age = new int(*p.m_age);
return *this;//返回自身,实现连等运算
}
};
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();
return 0;
}