Advertisement
AlexDanilin

Перегрузка операторов. Урок 3

Jun 14th, 2023
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. //Перегрузка операторов. Урок 3
  2. #include <iostream>
  3. #include <numeric>
  4. #include <vector>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. class Rational {
  10. public:
  11.     Rational() = default;
  12.  
  13.     Rational(int numerator)
  14.         : numerator_(numerator)
  15.         , denominator_(1)
  16.     {
  17.     }
  18.  
  19.     Rational(int numerator, int denominator)
  20.         : numerator_(numerator)
  21.         , denominator_(denominator)
  22.     {
  23.         Normalize();
  24.     }
  25.  
  26.     int Numerator() const {
  27.         return numerator_;
  28.     }
  29.  
  30.     int Denominator() const {
  31.         return denominator_;
  32.     }
  33.  
  34. private:
  35.     void Normalize() {
  36.         if (denominator_ < 0) {
  37.             numerator_ = -numerator_;
  38.             denominator_ = -denominator_;
  39.         }
  40.         int n = gcd(numerator_, denominator_);
  41.         numerator_ /= n;
  42.         denominator_ /= n;
  43.     }
  44.  
  45.     int numerator_ = 0;
  46.     int denominator_ = 1;
  47. };
  48.  
  49. ostream& operator<<(ostream& output, Rational rational) {
  50.     output << rational.Numerator() << '/' << rational.Denominator();
  51.     return output;
  52. }
  53.  
  54. istream& operator>>(istream& input, Rational& rational) {
  55.     int numerator, denominator;
  56.     char slash;
  57.     input >> numerator >> slash >> denominator;
  58.     rational = Rational{numerator, denominator};
  59.     return input;
  60. }
  61.  
  62.  
  63. Rational operator+(Rational left, Rational right) {
  64.     const int numerator = left.Numerator() * right.Denominator()
  65.         + right.Numerator() * left.Denominator();
  66.     const int denominator = left.Denominator() * right.Denominator();
  67.  
  68.     return { numerator, denominator };
  69. }
  70.  
  71. Rational operator-(Rational left, Rational right) {
  72.     const int numerator = left.Numerator() * right.Denominator()
  73.         - right.Numerator() * left.Denominator();
  74.     const int denominator = left.Denominator() * right.Denominator();
  75.  
  76.     return { numerator, denominator };
  77. }
  78.  
  79. Rational operator-(Rational value) {
  80.     return { -value.Numerator(), value.Denominator()};
  81. }
  82.  
  83. Rational operator+(Rational value) {
  84.     return value;
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement