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?
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.
Output streams use the insertion ( << ) operator for standard types. You can also overload the << operator for your own classes.
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 (.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With