Advertisement
Alaricy

перегрузка арифм операторов

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