1、成员函数版本实现算术运算符的重载;全局函数版本实现算术运算符的重载
#include <iostream>using namespace std;class Test
{friend const Test operator-(const Test &L,const Test &R);
private:int c;int n;
public:Test(){}Test(int c,int n):c(c),n(n){}//类内成员函数实现+运算符重载const Test operator+(const Test &T)const{Test temp;temp.c = c+T.c;temp.n = n+T.n;return temp;}void show(){cout << "c = " << c << "n = " << n << endl;}
};
//全局函数实现—运算符重载
const Test operator-(const Test &L,const Test &R)
{Test temp;temp.c = L.c-R.c;temp.n = L.n-R.n;return temp;
}int main()
{Test t1('K',4);Test t2('Y',8);Test t3 = t1 + t2;t3.show();Test t4 = t1 - t2;t4.show();return 0;
}
2、思维导图