运算符重载(加号)

加号运算符重载

  • 作用:实现两个自定义数据类型相加的运算

  • 方法: 返回值 operator +(形参列表)

    (1)通过成员函数重载 + 号

    (2)全局函数重载 + 号

示例:

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_a;
int m_b;
Person() {
}
Person(int a, int b):m_a(a),m_b(b){}
//通过成员函数重载 + 号
Person operator + (Person &p1) {
Person temp;
temp.m_a = this->m_a + p1.m_a;
temp.m_b = this->m_b + p1.m_b;
return temp;
}
};
//全局函数重载
//Person operator + (Person& p1, Person& p2) {
// Person temp;
// temp.m_a = p1.m_a + p1.m_a;
// temp.m_b = p2.m_b + p1.m_b;
// return temp;
//}
void test01() {
Person p1(10,10);
Person p2(10,10);
Person p3 = p1 + p2;
//成员函数调用本质:Person p3 = p1.operator+(p2);
cout << p3.m_a << " " << p3.m_b << endl;
Person p4 = p1 + p2;
//全局函数本质调用:Person p4 = operator+(p1,p2);
cout << p3.m_a << " " << p3.m_b << endl;
}
int main() {
test01();
return 0;
}
  • 运算符重载也可以实现函数重载
1
2
3
4
Person operator + (Person& p1, Person& p2) {
}
Person operator + (Person& p1, int a){
}