运算符重载(++ --)

#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){}


friend ostream& operator<<(ostream& o,const F& f)
{
o<<f.n<<'/'<<f.d;
return o;
}
F& operator++(){n+=d;return *this;}//前++
F operator++(int){F old(*this);n += d;return old;}//后++带int参数 为哑元函数
friend F& operator--(F& f){f.n -= f.d;return f;}
friend F operator--(F& f,int){F old(f);f.n -= f.d;return old;}
operator double(){return 1.0*n/d;}
operator bool(){return n != 0;}
};
void fun(F a){cout<<a<<endl;}
int main()
{
F f1(2,5),f2(4,9),f3(17,3);
cout<<++f1<<endl;//f1.operator++();
cout<<f2++<<endl;//f2.operator++(0);
cout<<"f1 = "<<f1<<",f2 = "<<f2<<endl;
cout<<--f3<<endl;//operator--(f3)
cout<<f3--<<endl;//operator--(f3,0)
cout<<"f3 = "<<f3<<endl;
cout<<double(f1)<<endl;//f1.operator double();
cout<<boolalpha<<(bool)f3<<endl;//f3.operator bool();
cout<<F(5)<<endl;
cout<<(F)3<<endl;
fun(7);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值