Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of unary plus operator

Tags:

c++

I've heard it is used as overloaded operator+ for example

class MyClass
{
    int x;
public:
    MyClass(int num):x(num){}
    MyClass operator+(const MyClass &rhs)
    {
        return rhs.x + x;
    }
};

int main()
{
    MyClass x(100);
    MyClass y(100);
    MyClass z = x + y;
}

Is this really the use of unary plus operator or is it really a binary + operator?

like image 966
user2133 Avatar asked Feb 25 '11 13:02

user2133


2 Answers

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;
}
like image 68
Johannes Schaub - litb Avatar answered Oct 23 '22 04:10

Johannes Schaub - litb


That's a binary + operator. To overload the unary plus operator, you'd need something like this.

like image 25
Roger Lipscombe Avatar answered Oct 23 '22 05:10

Roger Lipscombe