Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator << must take exactly one argument

a.h

#include "logic.h" ...  class A { friend ostream& operator<<(ostream&, A&); ... }; 

logic.cpp

#include "a.h" ... ostream& logic::operator<<(ostream& os, A& a) { ... } ... 

When i compile, it says:

std::ostream& logic::operator<<(std::ostream&, A&)' must take exactly one argument.

What is the problem?

like image 558
As As Avatar asked May 24 '12 20:05

As As


People also ask

What is << operator C++?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

Can we overload << operator?

Output streams use the insertion ( << ) operator for standard types. You can also overload the << operator for your own classes.

Can we overload << operator in C ++?

Can we overload all operators? Almost all operators can be overloaded except a few. Following is the list of operators that cannot be overloaded. sizeof typeid Scope resolution (::) Class member access operators (.

Could we define operator << as a member function?

You can not do it as a member function, because the implicit this parameter is the left hand side of the << -operator. (Hence, you would need to add it as a member function to the ostream -class.


1 Answers

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ }; std::ostream& operator<<(std::ostream&, const A& a); 
like image 178
Cat Plus Plus Avatar answered Sep 30 '22 20:09

Cat Plus Plus