How to overload unary minus operator in C++?

前端 未结 2 1007
遥遥无期
遥遥无期 2020-11-30 01:46

I\'m implementing vector class and I need to get an opposite of some vector. Is it possible to define this method using operator overloading?

Here\'s what I mean:

相关标签:
2条回答
  • 2020-11-30 02:01

    It's

    Vector2f operator-(const Vector2f& in) {
       return Vector2f(-in.x,-in.y);
    }
    

    Can be within the class, or outside. My sample is in namespace scope.

    0 讨论(0)
  • 2020-11-30 02:16

    Yes, but you don't provide it with a parameter:

    class Vector {
       ...
       Vector operator-()  {
         // your code here
       }
    };
    

    Note that you should not return *this. The unary - operator needs to create a brand new Vector value, not change the thing it is applied to, so your code may want to look something like this:

    class Vector {
       ...
       Vector operator-() const {
          Vector v;
          v.x = -x;
          v.y = -y;
          return v;
       }
    };
    
    0 讨论(0)
提交回复
热议问题