Overloading the + (or any other binary operator) using a friend allows a built-in type to occur on the left or right side of the operator. : Plus « Overload « C++






Overloading the + (or any other binary operator) using a friend allows a built-in type to occur on the left or right side of the operator.

  
#include <iostream>  
using namespace std;
class MyClass {  
public:  
  int count;  
  MyClass operator=(int i);  
  friend MyClass operator+(MyClass ob, int i);  
  friend MyClass operator+(int i, MyClass ob);  
};  
     
MyClass MyClass::operator=(int i)  
{  
  count = i;  
  return *this;  
}  
     
// This handles ob + int.  
MyClass operator+(MyClass ob, int i)  
{  
  MyClass temp;  
     
  temp.count = ob.count + i;  
  return temp;  
}  
     
// This handles int + ob.  
MyClass operator+(int i, MyClass ob)  
{  
  MyClass temp;  
     
  temp.count = ob.count + i;  
  return temp;  
}  
     
main(void)  
{  
  MyClass obj;  
  obj = 10;  
  cout << obj.count << " "; 
     
  obj = 10 + obj; 
  cout << obj.count << " "; 
     
  obj = obj + 12; 
  cout << obj.count;
     
  return 0;  
}
  
    
  








Related examples in the same category

1.Overload the + relative to MyClass.Overload the + relative to MyClass.
2.Overload + for 'ob + int' as well as 'ob + ob'.Overload + for 'ob + int' as well as 'ob + ob'.
3.String class with custom +/- operator
4.additional meanings for the + and = operations
5.overload the "+" operator so that several angles, in the format degrees minutes seconds, can be added directly.
6.Friendly operator+
7.overloaded '+' operator adds two Distances
8.overloaded '+' operator concatenates strings
9.+ is overloaded for three_d + three_d and for three_d + int.
10.Define operator +(plus) and cast to double operator
11.friend overloaded + operator