对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

  • 总结:
  1. 对于内置的数据类型的表达式的运算符是不可能改变的
  2. 不要滥用运算符重载

直接进行加法运算

  • 报错
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    #include <iostream>
    using namespace std;

    class Person {
    public:
    int m_A;
    int m_B;
    };
    int main(){
    Person p1;
    Person p2;
    p1.m_A = 10;
    p2.m_A = 20;
    p1.m_B = 30;
    p2.m_B = 40;
    Person p3 = p1 + p2;//报错
    cout << "p3.m_A=" << p3.m_A << endl;
    cout << "p3.m_B=" << p3.m_B << endl;
    return 0;
    }

使用自己的成员函数进行运算

  • 正常
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
#include <iostream>
using namespace std;

class Person {
public:
Person personAddPerson(Person &p) {
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
int m_A;
int m_B;
};
int main(){
Person p1;
Person p2;
p1.m_A = 10;
p2.m_A = 20;
p1.m_B = 30;
p2.m_B = 40;
Person p3 = p1.personAddPerson(p2);//正常
cout << "p3.m_A=" << p3.m_A << endl;
cout << "p3.m_B=" << p3.m_B << endl;
return 0;
}
  • 不可写成p3=p1+p2;

使用编译器提供的的函数名

  • 可写成p3=p1+p2;

成员函数

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
#include <iostream>
using namespace std;

class Person {
public:
Person operator+ (Person &p) {
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
int m_A;
int m_B;
};
int main(){
Person p1;
Person p2;
p1.m_A = 10;
p2.m_A = 20;
p1.m_B = 30;
p2.m_B = 40;
Person p3 = p1 + p2;//正常
//相当于Person p3=p1.operator+(p2);
cout << "p3.m_A=" << p3.m_A << endl;
cout << "p3.m_B=" << p3.m_B << endl;
return 0;
}

全局函数

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
#include <iostream>
using namespace std;

class Person {
public:

int m_A;
int m_B;
};
Person operator+ (Person& p1,Person &p2) {
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
int main(){
Person p1;
Person p2;
p1.m_A = 10;
p2.m_A = 20;
p1.m_B = 30;
p2.m_B = 40;
Person p3 = p1 + p2;//正常
//相当于Person p3=operator+(p1,p2);
cout << "p3.m_A=" << p3.m_A << endl;
cout << "p3.m_B=" << p3.m_B << endl;
return 0;
}

自定义 + int

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
#include <iostream>
using namespace std;

class Person {
public:

int m_A;
int m_B;
};
Person operator+ (Person& p1,int num) {
Person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
int main(){
Person p1;
Person p2;
p1.m_A = 10;
p2.m_A = 20;
p1.m_B = 30;
p2.m_B = 40;
Person p3 = p1 + 50;//正常
cout << "p3.m_A=" << p3.m_A << endl;
cout << "p3.m_B=" << p3.m_B << endl;
return 0;
}