Advertisement
shchuko

OperatorOverloadExample

Mar 20th, 2020
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4.  
  5.  
  6. class C {
  7. private:
  8.     int x = 10;
  9.    
  10. public:
  11.     C() {
  12.         std::cout << "Build C without x" << std::endl;
  13.  
  14.     }
  15.    
  16.    
  17.     C(int _x) : x {_x } {
  18.         std::cout << "Build C with x" << std::endl;
  19.     }
  20.    
  21.    
  22.     C sub(const C& c) const {
  23.         int x_value = x - c.x;
  24.         return  C(x_value);
  25.     }
  26.    
  27.     int getX() const {
  28.         return x;  
  29.     }
  30.    
  31.    
  32.     C operator-() const {
  33.         int new_x = -getX();
  34.         return C(new_x);
  35.     }
  36.    
  37.     C operator+() const {
  38.         int new_x = getX();
  39.         return C(new_x);
  40.     }
  41.    
  42.     C& operator-=(const C& c) {
  43.         x -= c.x;
  44.         return *this;
  45.     }
  46.    
  47.     friend C operator+(const C& left, const C& right);
  48.     friend C operator-(const C& left, const C& right);
  49.    
  50.  
  51. };
  52.  
  53. C operator+(const C& left, const C& right) {
  54.     return C(left.getX() + right.getX());  
  55. }
  56.  
  57. C operator-(const C& left, const C& right) {
  58.     return C(left.getX() - right.getX());  
  59. }
  60.  
  61. int main()
  62. {
  63.     C a;
  64.     C b;
  65.    
  66.     auto var = a + b;
  67.    
  68.     std::cout << var.getX() << std::endl;
  69.     var -= a;
  70.     std::cout << var.getX() << std::endl;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement