I\'ve heard it is used as overloaded operator+ for example
class MyClass
{
int x;
public:
MyClass(int num):x(num){}
MyClass operator+(const MyCla
When an operator-function is a member function, it has one more argument (this
) than explicitly mentioned in the declaration. So in your case it's the binary +, the first argument is this
, the second is the passed argument.
This is not overloading and using unary + .. You need to either make that a free function or make the member function take 0 arguments
class MyClass
{
int x;
public:
MyClass(int num):x(num){}
MyClass operator+() const
{
return *this;
}
};
int main() {
MyClass x = 42;
+ x;
}
That's a binary + operator. To overload the unary plus operator, you'd need something like this.
This has been asked a few times before.
Your operator+ is binary. If defined as a member function needs to be const.
class MyClass
{
int x;
public:
MyClass(int num):x(num){}
MyClass operator+(const MyClass &rhs) const
{
return rhs.x + x;
}
};
It is quite often implemented in terms of operator +=
Note you have switched the commutativity but it will work as + for int is commutative.
A unary+ operator as a member would take no parameters and would not modify the object thus should be const. The implementation is up to your object. You could use it as "abs" for your int. (Using it as a no-op serves little purpose).
MyClass MyClass::operator+() const
{
return ( x >= 0 ) ? MyClass( x ) : MyClass(-x);
}