Reputation: 3875
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.
Upvotes: 2
Views: 2284
Reputation: 11416
Make the operator+
overload with int
on the left hand side a free function instead of a member function of MyType
:
class MyType
{
...
// MyType + int can be a member function because MyType
// is the type of the sum's left hand side
MyType operator+(int rhs) const;
};
// int + MyType needs to be a free function because
// int is the type of the sum's left hand side
MyType operator+(int lhs, const MyType &rhs);
Another common idiom is to make the overloads a friend
of the class of interest. Now you can implement both cases in the same way:
class MyType
{
...
friend MyType operator+(int lhs, const MyType &rhs)
{
// get access to MyType's private members here
// to implement the sum operation
...
}
friend MyType operator+(const MyType &lhs, int rhs)
{
// you can also implement the symmetric case
// of int on the right hand side here
...
}
};
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 as friend
s of MyType
.
Upvotes: 3
Reputation: 8604
You can define an operator in the global scope in C++, e.g.
MyType operator+ (const MyType& a, const MyType& b)
{
MyType ret;
/* do something*/
return ret;
}
You may need to add a friend declaration to MyType
if the operator should access private members of the class.
Upvotes: 3