0

I was wondering how many parameters can an overloaded operator take in C++?

I've seen operators take both one and two parameters, so I wanted to know if they can take both or just one, specifically for the - and << operators.

Jongware
  • 22,200
  • 8
  • 54
  • 100
  • `<<` - No. That would be syntax error. `-` - yes, [there is an unary minus operator](http://stackoverflow.com/questions/2155275/how-to-overload-unary-minus-operator-in-c). – Elazar Jun 07 '15 at 23:49
  • .. Actually, [Is it possible to overload operator associativity in C++?](http://stackoverflow.com/a/21445933/2564301) has a better answer: "Overloaded operators obey the rules for syntax specified in Clause 5." – Jongware Jun 07 '15 at 23:55

2 Answers2

1

The << always takes one parameter. E.g. with x << y, x would be the instance operator<<() is called from and y would be its parameter. Of course, you could overload the operator with different types of y, but always only one.

The - operator has two flavors, and is indeed overloaded with different number of arguments:

  1. Unary (-x)
  2. Binary (x - y)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

For the minus operator, it can only take one parameter like so:

object& operator-(const object &ref); //please note the syntax and use of const

For the << operator (called ostream), you overload it like so, it takes two parameters:

friend ostream& operator<<(ostream &str, const object &ref);

Hope that answers your question.

Karim O.
  • 1,325
  • 6
  • 22
  • 36