Use of unary plus operator

前端 未结 4 1257
抹茶落季
抹茶落季 2021-01-04 19:09

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         


        
相关标签:
4条回答
  • 2021-01-04 19:31

    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.

    0 讨论(0)
  • 2021-01-04 19:33

    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;
    }
    
    0 讨论(0)
  • 2021-01-04 19:34

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

    0 讨论(0)
  • 2021-01-04 19:49

    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 讨论(0)
提交回复
热议问题