运算符重载2

#include<iostream>
using namespace std;


class F{
int n;
int d;
private:
void reduce()
{
int mcd = maxcd(n<0?-n:n,d);
if(mcd != 1) n/=mcd,d/=mcd;
}
public:
static int maxcd(int a,int b)//静态成员函数 工具函数 不依赖于某个对象
{//没有当前对象 没有this
if(0 == a) return b;
else{
return maxcd(b%a,a);
}
}
F(int n = 0,int d = 1):n(n),d(d)
{
if(0 == d)
throw "分母不能为0";
if(d<0) this->d= -d,F::n= -n;
reduce();
cout<<"F("<<n<<'/'<<d<<")\n";
}
friend ostream& operator<<(ostream& o,const F& f)
{
o<<f.n<<'/'<<f.d;
return o;
}
friend F operator+(const F& lh,const F& rh)//引用常量或者临时值必须有const
{
return F (lh.n*rh.d+lh.d*rh.n,lh.d*rh.d);//匿名对象 只用一次
}
F operator*(const F& rh)const//f1*f2可以用f1.operator(f2)这种来表示 其中f1不变 ()后加const
{
F res(rh.n*n,rh.d*d);
return res;
}
friend F operator~(const F& f);
bool operator!();
};
F operator~(const F& f)
{
return F(f.d,f.n);
}
bool F::operator!()
{
return !n;//(0 == n);
}


int main()
{
F f1(6,8);
F f2(6,-9);
F f3(-6,12);
cout<<f1<<','<<f2<<','<<f3<<endl;//operator<<(cout,f3);
cout<<F::maxcd(392,856)<<endl;//f1.maxcd(236,394);
//F::maxcd();=>obj.func=>Typeof(obj)::funnc
cout<<f1+f2<<endl;//用f1+f2+f3中f1+f2返回的是临时值 所以必须有const才能继续+f3
cout<<f1*f2<<','<<f2*f3<<endl;

cout<<"f1 = "<<f1<<endl;
cout<<"~f1 = "<<~f1<<endl;//operator~(f1)
cout<<"!f1 = "<<!f1<<endl;//f1.operator!();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值