1

Possible Duplicate:
How to overload unary minus operator in C++?

I have a class C that overloads a number of operators:

class C
{
  ...
  C& operator-=(const C& other) {...}
  const C operator-(const C& other) {...}
}
inline const C operator*(const double& lhs, const C& rhs)

Now I wanted to invert an object of type C

c = -c;

And gcc gives me the following error:

no match for >>operator-<< in >>-d<<
candidate is: const C C::operator-(const C&)

Using c = -1*c works, but I'd like to be able to shorten that. What's missing in my class?


Solved: added the unary operator-:

C operator-() const {...}

as a member of C.

1
  • My situation was slightly different - I didn't know I had to overload the unary operator. Commented Nov 29, 2012 at 18:28

3 Answers 3

5

You overloaded the binary - operator. What you also need is to overload the unary - operator

See

How to overload unary minus operator in C++?

for how to overload the unary - operator

Sign up to request clarification or add additional context in comments.

Comments

3

You overloaded binary -, binary * and compound assignment -= operators. Expression c = -c uses unary -, which you never overloaded.

If you want to overload unary - by a standalone (maybe friend) function, you have to declare it accordingly. It can be done inside class definition by simply adding a friend keyword

class C
{
  ...
  friend C operator-(const C& other) {...}
};

or by moving function declaration outside of the class definition

class C
{
  ...
};

inline C operator -(const C& other) {...}

Alternatively, if you want to declare unary - as a member, you have to declare it without parameters

class C
{
  ...
  C operator-() const {...}
};

Comments

0

Make this change :

const C operator-() {...}

1 Comment

Literally just changing the binary operator to unary would have broken quite a lot of my code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.