4

In C++, how are the operator overloading functions distinguished for the unary and binary minus operators?

I am trying to overload both with the following code:

Vector Vector::operator-(){
  return Vector(-x,-y,-z);
}

Vector Vector::operator-(const Vector& v){
  return this* + (-v);
}

But this spews a lot of errors:

vector.cpp: In member function ‘Vector Vector::operator-(const Vector&)’:
vector.cpp:88:20: error: passing ‘const Vector’ as ‘this’ argument of ‘Vector Vector::operator-()’ discards qualifiers [-fpermissive]
   return this* + (-v);
                    ^
vector.cpp:88:16: error: no match for ‘operator+’ (operand type is ‘Vector’)
   return this* + (-v);
                ^
vector.cpp:88:16: note: candidates are:
vector.cpp:70:8: note: Vector Vector::operator+(const Vector&)
 Vector Vector::operator+(const Vector& v){
        ^
...

How do I fix this problem?

1
  • 2
    Implement as a free function, not a member function. Or (if you insist on implementing as a member function) mark it as a const member function, i.e. Vector Vector::operator-(const Vector&) const; and Vector Vector::operator-() const;` Commented May 27, 2016 at 15:18

1 Answer 1

6

1.v is passed by reference to const, it can't be called with non-const member function. Since operator- and operator+ (both unary and binary version) doesn't modify members of class, you should make them const member functions.

Vector Vector::operator-() const {
  return Vector(-x,-y,-z);
}

2.Change

return this* + (-v);

to

return *this + (-v);
Sign up to request clarification or add additional context in comments.

1 Comment

@brandbest1 It's just a syntax error. this* + (-v); will call unary operator- on v, and call unary operator+ on the returned value, then failed since you only define a binary operator+. *this + (-v) will call unary operator- on v, and *this will dereference this and then call binary operator+ with them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.