avr39ripe

cppFractionCopyConstructor

Jul 13th, 2021
904
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class Fraction
  4. {
  5.     int numerator;
  6.     int denominator;
  7. public:
  8.     Fraction(int numeratorP, int denominatorP) : numerator{ numeratorP }, denominator{ denominatorP }
  9.     {
  10.         std::cout << "Fraction constructed for -> " << this << '\n';
  11.     }
  12.     //  Fraction f3{ f1 };
  13.     Fraction(const Fraction& fract) : numerator{ fract.numerator }, denominator{ fract.denominator }{ std::cout << "Fraction COPY constructed for -> " << this << '\n'; }
  14.    
  15.     Fraction() :Fraction(1, 1) { std::cout << "Fraction DEFAULT constructed for -> " << this << '\n'; }
  16.    
  17.     int getNumerator() { return numerator; }
  18.     int getDenominator() { return denominator; }
  19.  
  20.     void setNumerator(int num) { numerator = num; }
  21.     void setDenominator(int denom) { denominator = denom; }
  22.  
  23.     Fraction mul(const Fraction& frac)
  24.     {
  25.         return Fraction{ numerator * frac.numerator, denominator * frac.denominator };
  26.     }
  27.  
  28.     Fraction div(const Fraction& frac)
  29.     {
  30.         return Fraction{ numerator * frac.denominator, denominator * frac.numerator};
  31.     }
  32.  
  33.     Fraction& print()
  34.     {
  35.         std::cout << '(' << numerator << '/' << denominator << ')';
  36.         return *this;
  37.     }
  38.  
  39.     ~Fraction()
  40.     {
  41.         std::cout << "Fraction destructed for -> " << this << '\n';
  42.     }
  43. };
  44.  
  45. int main()
  46. {
  47.     Fraction f1{1,3};
  48.     Fraction f2{1,2};
  49.  
  50.     Fraction f3{ f1 };
  51.  
  52.     Fraction f4{ f1.mul(f2) };
  53.  
  54.     f1.print(); std::cout << '\n';
  55.     f2.print(); std::cout << '\n';
  56.     f3.print(); std::cout << '\n';
  57.     f4.print(); std::cout << '\n';
  58.  
  59.  
  60.     return 0;
  61. }
RAW Paste Data