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-(InchSize rhs);
  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.
  32. InchSize InchSize::operator-(InchSize rhs) {
  33. InchSize totalSize;
  34.  
  35. totalSize.inches = inches - rhs.inches;
  36. totalSize.sixteenths = sixteenths - rhs.sixteenths;
  37.  
  38. // If sixteenths is negative, and we have at least 1 inch, carry 1 from inches.
  39. if (totalSize.sixteenths < 0 && totalSize.inches > 0) {
  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(1, 12);
  58. InchSize size2(4, 11);
  59. InchSize spaceAvailable(8, 6);
  60. InchSize sumSize;
  61. InchSize remainingSpace;
  62.  
  63. sumSize = size1 + size2;
  64. remainingSpace = spaceAvailable - sumSize;
  65.  
  66. remainingSpace.Print();
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
1 15/16 inches