运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型;
加号运算符重载
- 作用:实现两个自定义数据类型相加的运算;
- 这时需要定义成员函数重载+号或全局函数重载+号:
定义成员函数重载+号
注意:函数中要临时创建一个对象,用来存储操作过后的数据,然后再通过重载函数进行返回对象;
class Person
{
public:
1.成员函数重载+号
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;
}
Person() {
};
int m_A;
int m_B;
};
int main() {
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 10;
p2.m_B = 10;
Person p3