為了完成 Rational 類別的定義,我們將實作所需的建構子、多載運算子,以及 prt() 成員函數。在這個實作中,所有運算結果都將自動化簡為最簡分數。
以下是完整的 Rational 類別定義:
#include <iostream>
#include <numeric> // For std::gcd
class Rational {
private:
int a; // 分子
int b; // 分母
// Helper function to reduce the fraction to its simplest form
void reduce() {
int gcd = std::gcd(a, b); // Calculate the greatest common divisor of a and b
a /= gcd; // Divide both a and b by gcd to reduce the fraction
b /= gcd;
if (b < 0) { // Handle negative denominators
a = -a;
b = -b;
}
}
public:
// Default constructor that initializes the rational number as 0/1
Rational() : a(0), b(1) {}
// Constructor that takes two integers as numerator and denominator
Rational(int numerator, int denominator) : a(numerator), b(denominator) {
if (b == 0) {
throw std::invalid_argument("Denominator cannot be zero");
}
reduce(); // Reduce the fraction immediately upon construction
}
// Method to print the rational number
void prt() const {
std::cout << a << "/" << b;
}
// Overload the + operator to add two Rational numbers
Rational operator+(const Rational& rhs) const {
return Rational(this->a * rhs.b + rhs.a * this->b, this->b * rhs.b);
}
// Overload the - operator to subtract two Rational numbers
Rational operator-(const Rational& rhs) const {
return Rational(this->a * rhs.b - rhs.a * this->b, this->b * rhs.b);
}
// Overload the * operator to multiply two Rational numbers
Rational operator*(const Rational& rhs) const {
return Rational(this->a * rhs.a, this->b * rhs.b);
}
// Overload the / operator to divide two Rational numbers
Rational operator/(const Rational& rhs) const {
if (rhs.a == 0) {
throw std::invalid_argument("Cannot divide by Rational number with numerator 0");
}
return Rational(this->a * rhs.b, this->b * rhs.a);
}
};
int main() {
// Assume the input is provided in the command line arguments
Rational r0;
std::cout << "r0 = "; r0.prt(); std::cout << std::endl;
Rational r1(2, 4);
std::cout << "r1 = "; r1.prt(); std::cout << std::endl;
Rational r2(3, 6);
std::cout << "r2 = "; r2.prt(); std::cout << std::endl;
Rational r3 = r1 + r2;
std::cout << "r1 + r2 = "; r3.prt(); std::cout << std::endl;
Rational r4 = r1 - r2;
std::cout << "r1 - r2 = "; r4.prt(); std::cout << std::endl;
Rational r5 = r1 * r2;
std::cout << "r1 * r2 = "; r5.prt(); std::cout << std::endl;
Rational r6 = r1 / r2;
std::cout << "r1 / r2 = "; r6.prt(); std::cout << std::endl;
return 0;
}
這段代碼中:
reduce() 是一個幫助函數,用於將分數化簡成最簡分數。
建構子會立即調用 reduce() 函數來確保對象始終保持在最簡分數形式。
prt() 函數用於輸出有理數的最簡分數形式。
運算子 +, -, *, / 被重載以實現有理數之間的算數