作用:实现两个自定义数据类型的相加运算
示例:
#include<iostream>
using namespace std;
class Building
{
public:
int m_age1;
int m_age2;
//成员函数重载+号。
// 成员函数重载本质调用
// Building operator+(Building &p)
// {
// Building temp;
// temp.m_age1=this->m_age1+p.m_age1;
// temp.m_age2=this->m_age2+p.m_age2;
// return temp;
// }
};
//全局函数重载+号
Building operator+(Building &p1,Building &p2)
{
Building temp;
temp.m_age1=p1.m_age1+p2.m_age1;
temp.m_age2=p1.m_age2+p2.m_age2;
return temp;
}
Building operator+(Building &p1,int num)
{
Building temp;
temp.m_age1=p1.m_age1+num;
temp.m_age2=p1.m_age2+num;
return temp;
}
void show()
{
Building p1;
p1.m_age1=10;
p1.m_age2=10;
Building p2;
p2.m_age1=10;
p2.m_age2=10;
// Building p3=p1+p2;
Building p3;
Building p4;
//成员函数重载本质调用
// p3=p1.operator+(p2);
//全局函数本质的调用
// p3=operator+(p1,p2);
// 简化版
p3=p1+p2;
p4=p1+100;//运算符重载也可以发生函数重载。
cout<<"p3.age1:"<<p3.m_age1<<endl;
cout<<"p3.age2:"<<p3.m_age2<<endl;
cout<<"p4.age1:"<<p4.m_age1<<endl;
cout<<"p4.age2:"<<p4.m_age2<<endl;
}
int main()
{
show();
return 0;
}