下面是 Rational 類的一個可能的 C++ 定義。這個定義包括了構造函數、一個私有的簡化函數、運算符重載,以及 prt 函數來輸出 Rational 對象。
cpp
Copy code
#include <iostream>
#include <numeric> // For std::gcd
class Rational {
private:
int a; // 分子
int b; // 分母
// Helper function to reduce the fraction
void reduce() {
int gcd = std::gcd(a, b); // Compute the greatest common divisor
a /= gcd; // Reduce the numerator by the gcd
b /= gcd; // Reduce the denominator by the gcd
}
public:
// Default constructor that initializes a rational number as 0/1
Rational() : a(0), b(1) {}
// Constructor that initializes the rational number with given numerator and denominator
Rational(int numerator, int denominator) : a(numerator), b(denominator) {
if (b == 0) {
throw std::invalid_argument("分母不能為 0");
}
reduce();
}
// Prints the rational number in the format a/b
void prt() const {
std::cout << a << "/" << b;
}
// Overload the + operator
Rational operator+(const Rational& rhs) const {
return Rational(this->a * rhs.b + rhs.a * this->b, this->b * rhs.b);
}
// Overload the - operator
Rational operator-(const Rational& rhs) const {
return Rational(this->a * rhs.b - rhs.a * this->b, this->b * rhs.b);
}
// Overload the * operator
Rational operator*(const Rational& rhs) const {
return Rational(this->a * rhs.a, this->b * rhs.b);
}
// Overload the / operator
Rational operator/(const Rational& rhs) const {
if (rhs.a == 0) {
throw std::invalid_argument("除數的分子不能為 0");
}
return Rational(this->a * rhs.b, this->b * rhs.a);
}
};
int main() {
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;
}
這個類別的定義包括了為 Rational 提供基本運算的運算子重載,如加法、減法、乘法和除法。請注意,所有的運算都會在構造時自動進行約分,以確保結果是簡化後的形式。此外,該程式碼包括了錯誤檢查,以防止分母為零或在除法中除以零的情況。這個類別定義不包括從命令行讀取數值的代碼;您需要將這部分代碼添加到 main 函數中,或者創建一個單獨的函數來處理輸入。