运算符重载的意义
为什么要有运算符重载?
因为我们无法对一个对象做加法,为了能够对对象做加法运算,左移运算右移运算。我们需要对运算符做重载。
如何进行运算符重载
- 局部运算符重载
class Person {
public:
int m_A;
int m_B;
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;
}
};
- 全局运算符重载
// 2. 全局函数重载+号
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;
}
什么情况不能进行运算符重载
C++自带的基本类型和数据结构不能够进行运算符重载
完整代码
#include<iostream>
using namespace std;
// 加号运算符重载
class Person {
public:
int m_A;
int m_B;
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;
}
};
// 1. 成员函数重载+号
// 2. 全局函数重载+号
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;
}
void test01() {
Person p1;
Person p2;
p1.m_A = 10;
p2.m_A = 10;
p1.m_B = 10;
p2.m_B = 10;
Person p3 = operator+(p1,p2);
/*Person p3 = p1 + p2;*/
}
int main(int argc,char* argv) {
test01();
system("pause");
return EXIT_SUCCESS;
}