实验目的和要求
掌握运算符重载的基本方法。
实验内容:
定义一个有理数类,并重载比较运算符<、<=、==、!=。
class Ration
{
public:
Ration(int num=0,int denom=1);
int operator<(Ration r) const;
int operator<=(Ration r) const;
int operator==(Ration r) const;
int operator!=(Ration r) const;
private:
long num,den;
};
代码
#include <iostream>
using namespace std;
class Ration
{
private:
int num,den;
public:
// 所需的构造函数
Ration(int num=0, int denom=1){
num=num;
den=denom;
}
// 重载小于运算符( < )
int operator <(Ration r)const
{
if(num < r.num)
{
return 1;
}
if(num == r.num && den < r.den)
{
return 1;
}
return 0;
}
// 重载小于等于运算符( <= )
int operator <=(Ration r)const
{
if(num <= r.num&&den <= r.den)
{
return 1;
}
return 0;
}
// 重载等于运算符( == )
int operator ==(Ration r)const
{
if(num == r.num&&den == r.den)
{
return 1;
}
return 0;
}
// 重载不等于运算符( != )
int operator !=(Ration r)const
{
if(num != r.num)
{
return 1;
}
if(den != r.den)
{
return 1;
}
return 0;
}
};
int main()
{
Ration D1(11, 10), D2(5, 11);
if( D1 < D2 )
{
cout << "D1 < D2 " << endl;
}
else
{
cout << "D2 < D1 " << endl;
}
if( D1 <= D2 )
{
cout << "D1 <= D2 " << endl;
}
else
{
cout << "D2 <= D1 " << endl;
}
if( D1 == D2 )
{
cout << "D1 == D2 " << endl;
}
else
{
cout << "D2 != D1 " << endl;
}
if( D1 != D2 )
{
cout << "D1 != D2 " << endl;
}
else
{
cout << "D2 = D1 " << endl;
}
return 0;
}