姬发是个怎样的人:C++的一道编程问题,请各位大侠指教

来源:百度文库 编辑:高校问答 时间:2024/04/28 12:33:11
已知一个有理数类Zrf_Ratio,实现如下的操作符重载形式:
friend std::ostream& operator<<(std::ostream&, const zrf_Ratio&);
friend std::istream& operator>>(std::istream&, zrf_Ratio&);
friend bool operator==(const zrf_Ratio&, const zrf_Ratio&);
friend bool operator<(const zrf_Ratio&, const zrf_Ratio&);
测试用主函数:
int main()
{
zrf_Ratio zrf(1,7),ssh(26,65);
std::cout<<"zrf is:"<<zrf<<"; ssh is:"<<ssh<<'\n' ;
std::cout<<"(zrf==ssh) is:"<<(zrf==ssh)<<"; (zrf<ssh) is:"<<(zrf<ssh) ;
return 0;

}
运行结果:
zrf is:1/7; ssh is:2/5
(zrf==ssh) is:0; (zrf<ssh) is:1
我是初学者,各位大侠帮个忙

//这道题目作出来了,和楼主给的运行结果完全相符
//呵呵,楼主这次题目我全给出可编译的代码,要给分哦!
//只要将代码拷贝就可以了,我已经编译运行成功!
#include <iostream>
class zrf_Ratio;
std::ostream& operator<<(std::ostream&, const zrf_Ratio&);
std::istream& operator>>(std::istream&, zrf_Ratio&);
bool operator==(const zrf_Ratio&, const zrf_Ratio&);
bool operator<(const zrf_Ratio&, const zrf_Ratio&);

class zrf_Ratio
{
private:
//一些友元运算符的重载

friend std::ostream& operator<<(std::ostream&, const zrf_Ratio&);
friend std::istream& operator>>(std::istream&, zrf_Ratio&);
friend bool operator==(const zrf_Ratio&, const zrf_Ratio&);
friend bool operator<(const zrf_Ratio&, const zrf_Ratio&);

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;
}

};
std::ostream &operator<<(std::ostream &stream,const zrf_Ratio& op)
{
stream<<op.top<<"/"<<op.bottom;
return stream;
}

std::istream& operator>>(std::istream &stream, zrf_Ratio& op)
{
stream>>op.top>>op.bottom;
return stream;
}

bool operator==(const zrf_Ratio&op1, const zrf_Ratio&op2)
{
return ((op1.top==op2.top)&&(op1.bottom==op2.bottom));
}
bool operator<(const zrf_Ratio&op1, const zrf_Ratio&op2)
{
return ((op1.top*op2.bottom)<(op2.top*op1.bottom));
}

int main()
{
zrf_Ratio zrf(1,7),ssh(26,65);
std::cout<<"zrf is:"<<zrf<<"; ssh is:"<<ssh<<'\n' ;
std::cout<<"(zrf==ssh) is:"<<(zrf==ssh)<<"; (zrf<ssh) is:"<<(zrf<ssh) ;

return 0;

}

这么简单,你白菜