为什么下面运算符重载可以通过编译却不能通过运行呀 求助 各位帮忙
#include<iostream.h>
#include<stdlib.h>
class FenShu{
friend ostream&operator<<(ostream&,const FenShu&);
private:
int a; //分子
int b; //分母
int k; //带分数的整数部分
public:
FenShu(int=0,int=1,int=0);
FenShu(FenShu&);
int getA()const;
int getB()const;
int getK()const;
const FenShu& operator=(const FenShu&);
FenShu operator+(FenShu&);
FenShu operator-(FenShu&);
FenShu operator*(FenShu&);
FenShu operator/(FenShu&);
};
ostream&operator<<(ostream &output,const FenShu &t)
{
output<<t.k<<"+"<<t.a<<"/"<<t.b<<endl;
return output;
}
FenShu::FenShu(int a1,int b1,int k1)
{
int t1=a1%b1,t2=b1,t;
while(t2%t1)
{
t=t2%t1;
t2=t1;
t1=t;
}
a=a1%b1/t1;b=b1/t1;
k=k1+a1/b1;
}
FenShu::FenShu(FenShu &t)
{
a=t.a;b=t.b;k=t.k;
}
int FenShu::getA()const{return a;}
int FenShu::getB()const{return b;}
int FenShu::getK()const{return k;}
const FenShu& FenShu::operator=(const FenShu &t)
{
if(&t!=this){
a=t.a;
b=t.b;
k=t.k;
}
return *this;
}
FenShu FenShu::operator+(FenShu &t)
{
FenShu t1;
t1.a=t.a*b+a*t.b;
t1.b=t.b*b;
t1.k=t.k+k;
return t1;
}
FenShu FenShu::operator-(FenShu &t)
{
return FenShu(a*t.b-t.a*b,t.b*b,k-t.k);
}
FenShu FenShu::operator*(FenShu &t)
{
return FenShu((t.k*t.b+t.a)*(k*b+a),t.b*b,0);
}
FenShu FenShu::operator/(FenShu &t)
{
return FenShu((k*b+a)*t.b,b*(t.k*t.b+t.a),0);
}
int main()
{
system("color 9c");
FenShu t1(112,24,12),t2(22,6,21);
cout<<"输出各分数为:\n";
FenShu t3,t4,t5,t6;
t3=t1;
t4=t1+t2;
t5=t2*t4;
t6=t2/t1;
cout<<"t1:"<<t1<<"\nt2:"<<t2<<"\nt3:"<<t3<<"\nt4:"<<t4<<"\nt5:"<<t5<<"\nt6:"<<t6<<endl;
system("pause");
return 0;
}
FenShu t3,t4,t5,t6; 这句
调用这个
FenShu::FenShu(int a1,int b1,int k1)//默认值 0,1,0
{
int t1=a1%b1,t2=b1,t;//t1=0
while(t2%t1) // t2/0异常了,除0
{
t=t2%t1;
t2=t1;
t1=t;
}
a=a1%b1/t1;b=b1/t1;
k=k1+a1/b1;
}
你看看这样会不会好一点:
if(t1!=0)
{
while(t2%t1)
{
t=t2%t1;
t2=t1;
t1=t;
}
}