早教吧 育儿知识 作业答案 考试题库 百科 知识分享

运算符重载构造一个分数类rationalNumber,该类中包括分子和分母两个成员数据,并具有下述功能:建立构造函数,它能防止分母为零,当分数不是最简形式时进行约分,并避免分母为负数重

题目详情
运算符重载
构造一个分数类rationalNumber,该类中包括分子和分母两个成员数据,并具有下述功能:
建立构造函数,它能防止分母为零,当分数不是最简形式时进行约分,并避免分母为负数
重载加法、减法、乘法以及除法运算符。
重载关系运算符:>、
▼优质解答
答案和解析
#include
using namespace std;
class rationalNumber{
private:
int a,b;
public:
rationalNumber(){}
rationalNumber(int m,int n){
if(m>0){
a=m;
b=n;
}
}
void display(){
cout< }

friend rationalNumber operator +(rationalNumber r1,rationalNumber r2);
friend rationalNumber operator -(rationalNumber r1,rationalNumber r2);
friend rationalNumber operator *(rationalNumber r1,rationalNumber r2);
friend rationalNumber operator /(rationalNumber r1,rationalNumber r2);
friend rationalNumber operator >(rationalNumber r1,rationalNumber r2);
friend rationalNumber operator friend rationalNumber operator ==(rationalNumber r1,rationalNumber r2);
};
rationalNumber operator +(rationalNumber r1,rationalNumber r2){
rationalNumber r;
r.a=r1.a*r2.a;
r.b=(r1.b*r2.a)+(r2.b*r1.a);
cout<}
rationalNumber operator -(rationalNumber r1,rationalNumber r2){
rationalNumber r;
r.a=r1.a*r2.a;
r.b=(r1.b*r2.a)-(r2.b*r1.a);
cout<}
rationalNumber operator *(rationalNumber r1,rationalNumber r2){
rationalNumber r;
r.a=r1.a*r2.a;
r.b=r1.b*r2.b;
cout<}
rationalNumber operator /(rationalNumber r1,rationalNumber r2){
rationalNumber r;
r.a=r1.a*r2.b;
r.b=r1.b*r2.a;
cout<}
rationalNumber operator >(rationalNumber r1,rationalNumber r2){
if((r1.b*r2.a)>(r1.a*r2.b)){
cout< }
else{
cout< }
}
rationalNumber operator if((r1.b*r2.a) cout< }
else{
cout< }
}
rationalNumber operator ==(rationalNumber r1,rationalNumber r2){
if((r1.b*r2.a)==(r1.a*r2.b)){
cout< }
}
void main()
{
int a,b;
cout< cin>>a;
cout< cin>>b;
rationalNumber r1(a,b);
r1.display();

int aa,bb;
cout< cin>>aa;
cout< cin>>bb;
rationalNumber r2(aa,bb);
r2.display();

operator +(r1,r2);
operator -(r1,r2);
operator *(r1,r2);
operator /(r1,r2);
operator >(r1,r2);
operator operator ==(r1,r2);

}