成员函数版本实现算术运算符的重载
全局函数版本实现算术运算符的重载
#include <iostream>
using namespace std;
class Number//定义一个数字类
{
//因为a和b是私有成员,全局进行访问需要要friend进行声明
friend const Number operator*(const Number &L,const Number &R);
friend const Number operator/(const Number &L,const Number &R);
private:
int a;
int b;
public:
//无参构造
Number(){}
//有参构造并列表初始化
Number(int a,int b):a(a),b(b)
{}
//成员函数实现+运算符重载
const Number operator+(const Number &R)const
{
Number sum;
sum.a=a+R.a;
sum.b=b+R.b;
return sum;
}
//成员函数实现-运算符重载
const Number operator-(const Number &R)const
{
Number sub;
sub.a=a-R.a;
sub.b=b-R.b;
return sub;
}
void show()//将结果显示出来
{
cout<<"a="<<a<<" "<<"b="<<b<<endl;
}
};
//全局函数实现*运算符重载
const Number operator*(const Number &L,const Number &R)
{
Number mul;
mul.a=L.a*R.a;
mul.b=L.b*R.b;
return mul;
}
//全局函数实现/运算符重载
const Number operator/(const Number &L,const Number &R)
{
Number divid;
divid.a=L.a/R.a;
divid.b=L.b/R.b;
return divid;
}
int main()
{
Number p1(55,7);
Number p2(8,6);
Number p3=p1+p2;
cout<<"p1的a,b"<<" ";//先将p1和p2的a,b打印出来,方便查看
p1.show();
cout<<"p2的a,b"<<" ";
p2.show();
cout<<"成员函数的+"<<" ";
p3.show();
cout<<"+++++++++++++++++++++"<<endl;
p3=p1-p2;
cout<<"成员函数的-"<<" ";
p3.show();
cout<<"+++++++++++++++++++++"<<endl;
p3=p1*p2;
cout<<"全局函数的乘"<<" ";
p3.show();
cout<<"+++++++++++++++++++++"<<endl;
p3=p1/p2;
cout<<"成员函数的/"<<" ";
p3.show();
return 0;
}