紫薇星与紫薇圣人:C++的一道编程问题,请各位大侠指教

来源:百度文库 编辑:高校问答 时间:2024/04/28 20:55:44
.已知一个有理数类Zrf_Ratio,实现如下的操作符重载形式:
zrf_Ratio& operator=(const zrf_Ratio&);
zrf_Ratio& operator*=(const zrf_Ratio&);
zrf_Ratio& operator++();
zrf_Ratio operator++(int);
int operator[](int);
测试用主函数:
int main()
{
zrf_Ratio zrf(1,7),ssh(26,65),zl;
zl=zrf;
std::cout<<"zrf is:"<<zrf<<"; ssh is:"<<ssh<<'\n' ;
std::cout<<"zl is:"<<zl;
std::cout<<"\nAfter zrf*=ssh, zrf is:"<< (zrf*=ssh);
std::cout<<"\nAfter zrf++ is:"<<zrf++ ;
std::cout<<"\nAfter ++zrf is:"<<++zrf ;
std::cout<<"\nzrf[1] is:"<<zrf[1]<<"; zrf[2] is:"<<zrf[2] ;
return 0;
}
运行结果:
zrf is:1/7; ssh is:2/5
zl is:1/7
After zrf*=ssh, zrf is:1/7
After zrf++ is:1/7
After ++zrf is:15/7
zrf[1] is:15; zrf[2] is:7

//终于搞定了 不过我不知道你的题目里的
//zrf*=ssh 的结果为什么还是1/7,应该是2/35吧?
//但是我的*=重载是按正常的方法重载的.
//实现了所有重载,我认为它们都是正确的,我已经调试运行成功
//该程序可直接拷贝使用
#include <iostream>
class zrf_Ratio;
std::ostream &operator<<(std::ostream &stream,zrf_Ratio op);
class zrf_Ratio
{
private:
friend std::ostream &operator<<(std::ostream &stream,zrf_Ratio op);
int top;
int bottom;
int show_b(int n,int m) //求最大公约数
{
int temp,r;
if(n<m)
{
temp=n;
n=m;
m=temp;
}
while(m)
{
r=n%m;
n=m;
m=r;
}
return n;
}
public:
zrf_Ratio(){};//缺省构造函数
zrf_Ratio(int itop,int ibottom):top(itop),bottom(ibottom)//构造函数
{
go_easy();
}
//化简函数
void go_easy()
{
int op1(top),op2(bottom);
if(op1<0)
op1=-op1;
if(op2<0)
op2=-op2;
int temp=show_b(op1,op2);
top/=temp;
bottom/=temp;
}
//一些运算符重载
zrf_Ratio& operator=(const zrf_Ratio &op)
{
top=op.top;
bottom=op.bottom;
return *this;
}
zrf_Ratio& operator*=(const zrf_Ratio&op)
{
top*=op.top;
bottom*=op.bottom;
go_easy();
return *this;
}
zrf_Ratio& operator++()
{
top+=bottom;
go_easy();
return *this;
}
zrf_Ratio operator++(int)
{
zrf_Ratio temp=*this;
top+=bottom;
go_easy();
return temp;
}
int operator[](int i)
{
if(i==1)
return top;
if(i==2)
return bottom;
//如果i的值非法返回0
std::cout<<"下标越界"<<std::endl;
return 0;
}

};
std::ostream &operator<<(std::ostream &stream,zrf_Ratio op)
{
stream<<op.top<<"/"<<op.bottom;
return stream;
}
int main()
{
zrf_Ratio zrf(1,7),ssh(26,65),zl;
zl=zrf;
std::cout<<"zrf is:"<<zrf<<"; ssh is:"<<ssh<<'\n' ;
std::cout<<"zl is:"<<zl;
//这个*=重载的调用被我注释了,你可以自行启用.
// std::cout<<"\nAfter zrf*=ssh, zrf is:"<< (zrf*=ssh);
std::cout<<"\nAfter zrf++ is:"<<zrf++ ;
std::cout<<"\nAfter ++zrf is:"<<++zrf ;
std::cout<<"\nzrf[1] is:"<<zrf[1]<<"; zrf[2] is:"<<zrf[2] ;
return 0;

}