fork download
  1. // "New" means new compared to previous level
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. class InchSize {
  6. public:
  7. InchSize(int wholeInches = 0, int sixteenths = 0);
  8. void Print() const;
  9. InchSize operator+(InchSize rhs);
  10. InchSize operator+(int sixteenthsOfInch);
  11. private:
  12. int inches;
  13. int sixteenths;
  14. };
  15.  
  16. InchSize InchSize::operator+(InchSize rhs) {
  17. InchSize totalSize;
  18.  
  19. totalSize.inches = inches + rhs.inches;
  20. totalSize.sixteenths = sixteenths + rhs.sixteenths;
  21.  
  22. // If sixteenths is greater than an inch, carry 1 to inches.
  23. if (totalSize.sixteenths >= 16) {
  24. totalSize.inches += 1;
  25. totalSize.sixteenths -= 16;
  26. }
  27.  
  28. return totalSize;
  29. }
  30.  
  31. // New: Overloaded + operator adding integers.
  32. InchSize InchSize::operator+(int sixteenthsOfInch) {
  33. InchSize totalSize;
  34.  
  35. totalSize.inches = inches;
  36. totalSize.sixteenths = sixteenths + sixteenthsOfInch;
  37.  
  38. // While sixteenths is greater than an inch, carry to inches.
  39. while (totalSize.sixteenths >= 16) {
  40. totalSize.inches += 1;
  41. totalSize.sixteenths -= 16;
  42. }
  43.  
  44. return totalSize;
  45. }
  46.  
  47. InchSize::InchSize(int wholeInches, int sixteenthsOfInch) {
  48. inches = wholeInches;
  49. sixteenths = sixteenthsOfInch;
  50. }
  51.  
  52. void InchSize::Print() const {
  53. cout << inches << " " << sixteenths << "/16 inches" << endl;
  54. }
  55.  
  56. int main() {
  57. InchSize size1(7, 13);
  58. InchSize size2(8, 14);
  59. InchSize sumSize;
  60. InchSize totalSize;
  61.  
  62. sumSize = size1 + size2;
  63. totalSize = sumSize + 22;
  64.  
  65. totalSize.Print();
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
18 1/16 inches