首页 新闻 赞助 找找看

运算符重载

0
悬赏园豆:100 [已解决问题] 解决于 2011-04-23 23:56

为什么下面运算符重载可以通过编译却不能通过运行呀   求助 各位帮忙
#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;
}

天极的主页 天极 | 初学一级 | 园豆:80
提问于:2011-04-15 22:44
< >
分享
最佳答案
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;
 }

收获园豆:100
lgz | 菜鸟二级 |园豆:265 | 2011-04-16 10:14
谢谢你了 你狠厉害呀
天极 | 园豆:80 (初学一级) | 2011-04-16 14:10
其他回答(1)
0

你看看这样会不会好一点:

if(t1!=0)

while(t2%t1)
  {
   t=t2%t1;
   t2=t1;
   t1=t;
  }
}

Alice Tang | 园豆:223 (菜鸟二级) | 2011-04-17 17:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册