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.

Community
  • 1
  • 1
Christoph
  • 1,040
  • 3
  • 14
  • 29

3 Answers3

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

Community
  • 1
  • 1
John Bandela
  • 2,416
  • 12
  • 19
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 {...}
};
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

Make this change :

const C operator-() {...}
asheeshr
  • 4,088
  • 6
  • 31
  • 50