1、成员函数版本实现算术运算符的重载 全局函数版本实现算术运算符的重载
#include <iostream>
using namespace std;
class Team
{
friend const Team operator-(const Team &t1, const Team &t2);
private:
int a;
int b;
public:
Team(){}
Team(int a, int b):a(a),b(b)
{}
//成员函数实现 +号 运算符重载
const Team operator+(const Team &t) const
{
Team temp;
temp.a = a + t.a;
temp.b = b + t.b;
return temp;
}
void show()
{
cout << "a = " << a << " b = " << b <<endl;
}
};
const Team operator-(const Team &t1, const Team &t2)
{
Team temp;
temp.a = t1.a - t2.a;
temp.b = t1.b - t2.b;
return temp;
}
int main()
{
Team t1(3,6);
Team t2(4,7);
Team t3 = t1 + t2;
t3.show();
Team t4 = t2 - t1;
t4.show();
return 0;
}
思维导图