下面是用类里的重载函数重载+号运算符
#include<iostream>
using namespace std;
class Person
{
public:
int m_A;
int m_B;
Person personaddperson(Person& p)//自己起名,实现类的加法
{
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = m_B + p.m_B;
return temp;
}
};
int main()
{
Person p1,p2,p3;
p1.m_A = 10;
p1.m_B = 10;
p2.m_A = 20;
p2.m_B = 30;
p3=p1.personaddperson(p2);
cout << p3.m_A;
}
然后把personaddperson重载函数名字改成operator+,就变成了标准的重载运算符
#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 = m_B + p.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 + p2.m_B;
return temp;
}//调用本质Person p3=operator+(p1,p2) 简化为Person p3=p1+p2
int main()
{
Person p1,p2,p3;
p1.m_A = 10;
p1.m_B = 10;
p2.m_A = 20;
p2.m_B = 30;
p3 = p1.operator+(p2);//等价于p1+p2
cout << p3.m_A;
}