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;
}
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。