c++ increment operator overload code example

Example 1: operator overloading in c++ <<

ostream &operator<<(ostream &output, const MyClass &myObject)
{ 
  output << "P : " << myObject.property;
  return output;            
}

Example 2: Operator overloading in C++ Programming

#include <iostream>
using namespace std;

class Test
{
   private:
      int count;

   public:
       Test(): count(5){}

       void operator ++() 
       { 
          count = count+1; 
       }
       void Display() { cout<<"Count: "<<count; }
};

int main()
{
    Test t;
    // this calls "function void operator ++()" function
    ++t;    
    t.Display();
    return 0;
}

Example 3: c++ over load operator

// This will substract one vector (math vector) from another
// Good example of how to use operator overloading

vec2 operator - (vec2 const &other) {
    return vec2(x - other.x, y - other.y);
}

Example 4: operator = overloading c++

inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){ return !(lhs == rhs); }

Example 5: operator ++ overloading c++

class Point
{
public:
	Point& operator++() { ... }		// prefix
	Point operator++(int) { ... }	// postfix
  	friend Point& operator++(Point &p);			// friend prefix
  	friend Point operator++(Point &p, int);		// friend postfix
  	// in Microsoft Docs written "friend Point& operator++(Point &p, int);"
};

Tags:

Cpp Example