//运算符重载要考虑形参(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)//引用不可改(f1+f2)+f3,,
//若要连加的话,(f1+f2)临时值就相当于const F &l,去掉const不可以,因为引用常量或临时值得加const
{
return F (l.n*r.d+r.n*l.d,l.d*r.d);
}
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);
}
};
int main(void)
{
F f1;
F f2(3,4);
F f3(8,12);
cout<<f2<<endl;
cout<<f3+f2<<endl;
return 0;
}
运算符重载小程序1
最新推荐文章于 2023-08-20 23:54:15 发布