开发者

Use of unary plus operator

开发者 https://www.devze.com 2023-02-13 05:10 出处:网络
I\'ve heard it is used as overloaded operator+ for example class MyClass { int x; public: MyClass(int num):x(num){}

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?


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.


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 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);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消