文章目录
运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
加号运算符重载
重载加号运算符的方法
- 成员函数重载+号
- 全局函数重载+号
注意:运算符重载,也可以发生函数重载
class Person
{
public:
int m_a;
int m_b;
//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 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;
}
//函数重载
Person operator+(Person& p1, int a)
{
Person temp;
temp.m_a = p1.m_a + a;
temp.m_b = p1.m_b + a;
return temp;
}
void test1()
{
Person p1;
Person p2;
p1.m_a = 10;
p1.m_b = 10;
p2.m_a = 20;
p2.m_b = 20;
//Person p3 = p1 + p2;
Person p4 = p1 + 100; // 操作类型为Person + int
cout << "p4.m_a = " << p4.m_a << endl;
cout << "p4.m_b = " << p4.m_b << endl;
}