代码缺少print函数的具体实现,以下是完整的Rational类的定义和成员函数的实现:
#include <iostream>
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
Rational() : numerator(0), denominator(1) {}
// 构造函数重载
Rational(int numerator, int denominator) : numerator(numerator), denominator(denominator) {
simplify(); // 约简
}
void print() const {
std::cout << numerator << "/" << denominator << std::endl;
}
// 辗转相除法求最大公约数
static int gcd(int a, int b) {
int c;
if (a < b) {
c = a;
a = b;
b = c;
}
while (b != 0) {
c = a % b;
a = b;
b = c;
}
return a;
}
// 约简有理数
void simplify() {
int g = gcd(numerator, denominator);
numerator /= g;
denominator /= g;
// 处理负号
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
// 运算符重载:加法
Rational operator+(const Rational& other) const {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return Rational(newNumerator, newDenominator);
}
// 运算符重载:减法
Rational operator-(const Rational& other) const {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return Rational(newNumerator, newDenominator);
}
// 运算符重载:乘法
Rational operator*(const Rational& other) const {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return Rational(newNumerator, newDenominator);
}
// 运算符重载:除法
Rational operator/(const Rational& other) const {
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return Rational(newNumerator, newDenominator);
}
};
int main() {
Rational r1(1, 2);
Rational r2(1, 3);
Rational r3 = r1 + r2;
r3.print(); // 输出:5/6
Rational r4 = r1 - r2;
r4.print(); // 输出:1/6
Rational r5 = r1 * r2;
r5.print(); // 输出:1/6
Rational r6 = r1 / r2;
r6.print(); // 输出:3/2
return 0;
}
在这段代码中,我们使用了成员函数和静态成员函数来实现有理数的运算符重载和约简。运算符重载函数返回一个新的有理数对象,并且使用该对象的构造函数进行初始化。同时,我们还在print函数前加上了const关键字,表示该函数不会修改对象的成员值。这是因为只是输出对象的值,并不会对其进行修改。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |