C++重載運算符實現分數加減乘除

本文實例為大傢分享瞭C++重載運算符實現分數加減乘除的具體代碼,供大傢參考,具體內容如下

實現結果如下圖所示:

代碼如下所示:

#include <iostream>
 
using namespace std;
 
class Rational {
public:
 Rational operator+(Rational rhs);
 Rational operator-(Rational rhs);
 Rational operator*(Rational rhs);
 Rational operator/(Rational rhs);
 Rational(int num, int denom);
 
private:
 void normalize(); //負責對分數做化簡工作
 
 int numerator;//分子
 int denominator;//分母
 
 friend std::ostream& operator<<(ostream& os, Rational f);
};
 
Rational::Rational(int num, int denom) {
 numerator = num;
 denominator = denom;
 
 normalize();
}
 
//隻允許分子為負數,若分母為負數則把負數挪到分子部分
//利用歐幾裡得算法將分數簡化
void Rational::normalize() {
 if (denominator < 0) {
  numerator = -numerator;
  denominator = -denominator;
 }
 
 //歐幾裡得算法
 int a = abs(numerator);
 int b = abs(denominator);
 
 //求出最大公約數,a
 //eg: a=12,b=9.
 //t=3 a=9 b=3
 //t=0 a=3 b=0
 while (b > 0) {
  int t = a % b;//t為餘數
  a = b; //a取除數
  b = t; //b取餘數
 }
 
 //分子、分母分別處以最大公約數
 numerator /= a;
 denominator /= a;
}
 
//重載運算符函數是類的成員函數
//分數是先通分再加減
// a*d+b*c / b*d
Rational Rational::operator+(Rational rhs) {
 int a = numerator;
 int b = denominator;
 int c = rhs.numerator;
 int d = rhs.denominator;
 
 return Rational(a*d+b*c,b*d);
}
Rational Rational::operator-(Rational rhs) {
 int a = numerator;
 int b = denominator;
 int c = rhs.numerator;
 int d = rhs.denominator;
 
 return Rational(a*d - b*c, b*d);
 
 /*
 **這裡有個偷懶的寫法
 rhs.numerator = -rhs.numerator;
 return operator+(rhs);
 */
}
Rational Rational::operator*(Rational rhs) {
 int a = numerator;
 int b = denominator;
 int c = rhs.numerator;
 int d = rhs.denominator;
 
 return Rational(a*c, b*d);
}
Rational Rational::operator/(Rational rhs) {
 int t = rhs.denominator;
 rhs.denominator = rhs.numerator;
 rhs.numerator = t;
 
 return operator*(rhs);
}
//該函數是友元函數,因此不用加空間域名
ostream& operator<<(ostream& os, Rational f);
 
int main() {
 Rational r1(4, 18);
 Rational r2(14, 18);
 
 cout << r1 << " + " << r2 << " = " << (r1 + r2) << endl;
 cout << r1 << " - " << r2 << " = " << (r1 - r2) << endl;
 cout << r1 << " * " << r2 << " = " << (r1 * r2) << endl;
 cout << r1 << " / " << r2 << " = " << (r1 / r2) << endl;
 
 system("pause");
 return 0;
}
 
ostream& operator<<(ostream& os, Rational f) {
 os << f.numerator << "/" << f.denominator;
 return os;
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: