自己编写的分数相加,运算符重载不太会,求改正
//定义分数类,可以用初值构造分数,保证其对象的分母不为0//重载加法运算符,即实现A+B运算(A、B是分数)
#include<iostream>
using namespace std;
class fenshu
{
public:
fenshu(int m,int z);
~fenshu(){};
friend fenshu operator+(fenshu &f1,fenshu &f2);
friend ostream & operator<<(ostream &out,fenshu &o);
private:
int fenzi;
int fenmu;
};
//实现
fenshu::fenshu(int m,int z)
{
fenmu=m;
fenzi=z;
if(fenmu==0)
{
cout<<"分母不能为零!";
}
else
{
cout<<"请重新输入一个分数:";
fenmu=m;
fenzi=z;
}
fenshu operator+(fenshu &f1,fenshu &f2)
{
return fenshu(f1.fenmu*f2.fenmu,f1.fenzi*f2.fenmu+f2.fenzi*f1.fenmu); //此处提示有错
}
ostream & operator<<(ostream &out,fenshu &o)
{
out<<o.fenzi<<"/"<<o.fenmu<<endl;
return out;
}
//主函数
int main()
{
fenshu f1,f2,f3;
cout<<"请输入分数f1的 分母(空格)分子:"<<endl;
cin>>f1;
cout<<"请输入分数f2的 分母(空格)分子:"<<endl;
cin>>f2;
f3=f1+f2;
cout<<"f1+f2="<<c3<<endl;
return 0;
}