fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class InchSize {
  5. public:
  6. InchSize(int wholeInches = 0, int sixteenths = 0);
  7. void Print() const;
  8. InchSize operator+(InchSize rhs);
  9. private:
  10. int inches;
  11. int sixteenths;
  12. };
  13.  
  14. InchSize InchSize::operator+(InchSize rhs) {
  15. InchSize totalSize;
  16.  
  17. totalSize.inches = inches + rhs.inches;
  18. totalSize.sixteenths = sixteenths + rhs.sixteenths;
  19.  
  20. // If sixteenths is greater than an inch, carry 1 to inches.
  21. if (totalSize.sixteenths >= 16) {
  22. totalSize.inches += 1;
  23. totalSize.sixteenths -= 16;
  24. }
  25.  
  26. return totalSize;
  27. }
  28.  
  29. InchSize::InchSize(int wholeInches, int sixteenthsOfInch) {
  30. inches = wholeInches;
  31. sixteenths = sixteenthsOfInch;
  32. }
  33.  
  34. void InchSize::Print() const {
  35. cout << inches << " " << sixteenths << "/16 inches" << endl;
  36. }
  37.  
  38. int main() {
  39. InchSize size1(4, 10);
  40. InchSize size2(8, 12);
  41. InchSize sumSize;
  42.  
  43. sumSize = size1 + size2;
  44.  
  45. sumSize.Print();
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
13 6/16 inches