加号运算符重载:
很简单,就是编辑器给起了一个通用名称,更加方便;
包括:成员函数重载、全局函数重载、运算重载的函数重载方式;
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
int m_a;
int m_b;
//成员函数的加号重载;
Person operator+(Person& p)
{
Person pt;
pt.m_a = m_a + p.m_a;
pt.m_b = m_b + p.m_b;
return pt;
}
};
//全局函数的加号重载
Person operator+(Person& p1,Person& p2)
{
Person pt;
pt.m_a = p2.m_a + p1.m_a;
pt.m_b = p2.m_b + p1.m_b;
return pt;
}
//运算符重载的函数重载;
Person operator+(Person& p1, int num)
{
Person pt;
pt.m_a = num + p1.m_a;
pt.m_b = num + p1.m_b;
return pt;
}
int main()
{
Person p1, p2,p3;
p1.m_a = 10;
p1.m_b = 10;
p2.m_a = 10;
p2.m_b = 10;
//p3 = p1.operator+(p2); 这是重载运算符+的本质;
//p3=operator+(p1, 100)
p3 = p1 + 100;
cout << "p3.m_a=" << p3.m_a << endl;
cout << "p3.m_b=" << p3.m_b << endl;
system("pause");
return 0;
}