c++定义一个有理数类,重载比较运算符进行数据成员的设置和输出
时间: 2023-11-27 13:49:42 浏览: 62
用C++编程的有理数类
以下是一个简单的有理数类的定义,其中重载了比较运算符。
```
#include <iostream>
using namespace std;
class Rational {
public:
Rational(int n = 0, int d = 1) : numerator(n), denominator(d) {}
bool operator==(const Rational& other) const {
return numerator == other.numerator && denominator == other.denominator;
}
bool operator<(const Rational& other) const {
return numerator * other.denominator < other.numerator * denominator;
}
bool operator>(const Rational& other) const {
return numerator * other.denominator > other.numerator * denominator;
}
friend ostream& operator<<(ostream& os, const Rational& r) {
os << r.numerator << "/" << r.denominator;
return os;
}
private:
int numerator;
int denominator;
};
int main() {
Rational r1(2, 3);
Rational r2(4, 5);
cout << "r1 = " << r1 << endl;
cout << "r2 = " << r2 << endl;
if (r1 == r2) {
cout << "r1 and r2 are equal" << endl;
} else if (r1 < r2) {
cout << "r1 is less than r2" << endl;
} else {
cout << "r1 is greater than r2" << endl;
}
return 0;
}
```
输出:
```
r1 = 2/3
r2 = 4/5
r1 is less than r2
```
阅读全文