VC6.0中,分数计算器,应该怎么定义整数类才能使派生分数类有效????
#include<iostream.h>void huajian(int x,int y)
{ int i=2;
for(i=2;;i++)
{
if((x%i==0)||(y%i==0))
{ x=x/i;
y=y/i;
}
}
}
class Zhengshu{
private:
int a;//分母
int b;//分子
public:
Zhengshu(int a=0,int b=1);
};
Zhengshu::Zhengshu(int a1,int b1)
{ a=a1;
b=b1;
}
class Fenshu:public Zhengshu{
public:
Fenshu(int a,int b):Zhengshu(a,b)
{}
Fenshu operator+(Fenshu f);
Fenshu operator-(Fenshu f);
Fenshu operator*(Fenshu f);
Fenshu operator/(Fenshu f);
friend operator>>(istream& in,Fenshu &f);
friend operator<<(ostream& out,Fenshu &f);
friend void jiancha(Fenshu &f); //异常处理
};
Fenshu Fenshu::operator +(Fenshu f)
{ Fenshu s;
s.a=a*f.b+b*f.a;
s.b=b*f.b;
return huajian(s.a,s.b);
}
Fenshu Fenshu::operator - (Fenshu f)
{ Fenshu s;
s.a=a*f.b-b*f.a;
s.b=b*f.b;
return huajian(s.a,s.b);
}
Fenshu Fenshu::operator *(Fenshu f)
{ Fenshu s;
s.a=a*f.a;
s.b=b*f.b;
return huajian(s.a,s.b);
}
Fenshu Fenshu::operator /(Fenshu f)
{ Fenshu s;
s.a=a*f.b;
s.b=b*f.a;
return huajian(s.a,s.b);
}
void jiancha(Fenshu &f)
{
try
{
cin>>f;
}
catch(int)
{
cout<<"分母不能为0,请重新输入:"<<endl;
cin>>f;
}
catch(char)
{
cout<<"分数格式不对,请重新输入:"<<endl;
cin>>f;
}
}
operator>>(istream& in,Fenshu &f)
{ in>>f.a>>f.b>>endl;
if(f.b==0)
{
throw f.b;
}
else if((f.a>='a')||(f.a<='z')||(f.b>='a')||(f.b<='z'))
{
throw f;
}
else
return in;
}
operator<<(ostream& out,Fenshu &f)
{ out<<f.a<<"/"<<f.b<<endl;
return out;
}
int main()
{ Fenshu a1,a2;
char k;
int m
cout<<"---------------------------------------"<<endl;
cout<<"【1】加法"<<"【2】减法"<<endl<<"【3】乘法"<<"【4】除法"<<endl<<"【5】退出"<<endl;
cout<<"---------------------------------------"<<endl;
do{
cout<<"请选择你的菜单(1~5):";
cin>>m;
if(m<1||m>5)
{ cout<<"无此选项,请重新输入!"
}
else
{
cout<<"请输入第一个分数:";
cin>>a1;
jiancha(a1);
cout<<"请输入第二个分数:";
cin>>a2;
jiancha(a2);
switch(m)
{
case(1):
cout<<"a1+a2="<<a1+a2<<endl;
break;
case(2):
cout<<"a1-a2="<<a1-a2<<endl;
break;
case(3):
cout<<"a1*a2="<<a1*a2<<endl;
break;
case(4):
cout<<"a1/a2="<<a1/a2<<endl;
break;
case(5):
return 0;
break;
}
}
}while(1);
}