In C#, to overload an operator such as ‘+’, ‘-‘ etc, I have to make the function a static member of the class:
class MyType
{
/*...*/
public static MyType operator+ (MyType a, MyType b)
{
MyType ret;
/* do something*/
return ret;
}
}
As far as I know, in C++ this is how I can overload an operator:
class MyType
{
/*...*/
public:
MyType operator+ (MyType b) // *this is the first operand
{
MyType ret;
/* do something*/
return ret;
}
};
The problem is that *this is the first operand, so the first operand must be of type MyType. For example, if I want to add MyType to an integer:
MyType a, b;
b = a + 1; // Valid
b = 1 + a; // Error
In C#, I can overload the ‘+’ operator for each case.
My question is: can I do in C++ the same as in C#, use static operators? As far as I know, there is one way to do that, with friend operators, but they are lost when inheriting the function.
Make the
operator+overload withinton the left hand side a free function instead of a member function ofMyType:Another common idiom is to make the overloads a
friendof the class of interest. Now you can implement both cases in the same way:Note that even though the
operator+overloads look like member functions in the 2nd example, they are actually free functions that live in the global scope due to their declaration asfriends ofMyType.