Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1.  
  2. class Cents
  3. {
  4. private:
  5. int m_cents;
  6.  
  7. public:
  8. Cents(int cents) { m_cents = cents; }
  9.  
  10. // add Cents + int using a friend function
  11. friend Cents operator+(const Cents &c1, int value);
  12.  
  13. // add int + Cents using a friend function
  14. friend Cents operator+(int value, const Cents &c1);
  15.  
  16.  
  17. int getCents() { return m_cents; }
  18. };
  19.  
  20. // note: this function is not a member function!
  21. Cents operator+(const Cents &c1, int value)
  22. {
  23. // use the Cents constructor and operator+(int, int)
  24. // we can access m_cents directly because this is a friend function
  25. return Cents(c1.m_cents + value);
  26. }
  27.  
  28. // note: this function is not a member function!
  29. Cents operator+(int value, const Cents &c1)
  30. {
  31. // use the Cents constructor and operator+(int, int)
  32. // we can access m_cents directly because this is a friend function
  33. return Cents(c1.m_cents + value);
  34. }
  35.  
  36. int main()
  37. {
  38. Cents c1 = Cents(4) + 6;
  39. Cents c2 = 6 + Cents(4);
  40.  
  41. std::cout << "I have " << c1.getCents() << " cents." << std::endl;
  42. std::cout << "I have " << c2.getCents() << " cents." << std::endl;
  43.  
  44. return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement