fork download
  1.  
  2. #include <iostream>
  3. using namespace std;
  4. class Fraction {
  5. protected:
  6. int n, d;
  7. int gcd(int N, int D) { return (N == 0? D: gcd(D%N, N)); }
  8. void restrict() {int t = gcd(this->n, this->d); this->n =this->n / t; this->d /= t;}
  9. public:
  10. Fraction(int n=1, int d=1 ): n(n), d(d) {restrict();}
  11. int getD() {return d;}
  12. int getN() {return n;}
  13.  
  14. friend Fraction operator*(const Fraction &, const Fraction &);
  15.  
  16. const Fraction operator+(const Fraction & y) { return Fraction(n * y.d + d * y.n, d * y.d); }
  17. const Fraction operator*(const Fraction & y) { return Fraction(n * y.n, d * y.d); }
  18.  
  19. Fraction operator*=(const Fraction & y) { n *= y.n; d *= y.d; restrict(); return *this;}
  20. const Fraction operator-() { return Fraction(-n, d); }
  21. Fraction operator++() { n += d; return *this;}
  22. const Fraction operator++(int) {n += d; return Fraction(n-d, d); }
  23.  
  24. friend std::ostream & operator<<(std::ostream &, const Fraction);
  25.  
  26. int sum(int b){
  27. return this->n+b;
  28. }
  29.  
  30. };
  31.  
  32. Fraction operator*(const Fraction & x, const Fraction & y) { return Fraction(x.n * y.n, x.d * y.d); }
  33.  
  34. std::ostream & operator<< (std::ostream & out, const Fraction x) {
  35. out << x.n << "/" << x.d;
  36. //out<<"Hello";
  37. return out;
  38. }
  39.  
  40. int main() {
  41. Fraction x(1,3),y(1,2);
  42. cout<<y+x<<endl;
  43. cout<<y*x<<endl;
  44. }
  45.  
  46.  
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
5/6
1/6