运算符重载小程序2

</pre><pre name="code" class="cpp">//运算符重载要考虑形参(const 引用)还有返回临时值不能用引用
//分数实现重载<< + - *  ~ ! =
#include <iostream>
using namespace std;

class F{
public:
	F(int n=0,int d=1):n(n),d(d){
		if(d==0) throw 0;
		if(d<0) this->d=-d,F::n=-n;//保证分母是正的
		reduce();
	};
	~F(){};
//<<
	friend ostream& operator<<(ostream &out,const F &f)
	{
		out<<f.n<<"/"<<f.d;
		return out;
	}
//+
	friend F operator+(const F &l,const F &r)
	{
		return F (l.n*r.d+r.n*l.d,l.d*r.d);
	}
//-
	friend F operator-(const F &l,const F &r)
	{
		return F (l.n*r.d-r.n*l.d,l.d*r.d);
	}
//*
	F operator*(const F & t)
	{
		return F (n*t.n,d*t.d);
	}
// /
//	F operator/(const F & t)
//	{
//		return (d*t.n,n*t.d);
//	}
//~
	friend F operator~(const F &f)
	{
		return F(f.d,f.n);
	}
//!
	friend bool operator!(const F &f);
//=
	void operator=(const F &c);

private:
	int n,d;
//约分
	void reduce(){
		int mcd=maxcd(n<0?-n:n,d);
		if(mcd!=1) n/=mcd,d/=mcd;
	};
//递归最大公约数
	static int maxcd (int a,int b){//静态成员函数不能用this
		if(a==0) return b;
		return maxcd(b%a,a);
	}
};
bool operator !(const F &f)
{
	return !f.n;
}
void F::operator =(const F &c)
{
	n=c.n;
	d=c.d;
}

int main(void)
{

	F f1(1,2),f2(3,4),f3;
	cout<<f2<<endl;

	cout<<f1+f2<<endl;//5/4
	cout<<f2-f1<<endl;//1/4
	cout<<f1*f2<<endl;//3/8

	cout<<~f2<<endl;//4/3
	cout<<!f2<<endl;//0
	f3=f2;
	cout<<f3<<endl;//3/4
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值