Reputation: 710
Code:
std::ostream& operator<<(std::ostream& os, const BmvMessage& bm);
I don't see anything incorrect, but it gives the following error:
error: `std::ostream& BMV::BmvMessage::operator<<(std::ostream&, const BMV::BmvMessage&)' must take exactly one argument.
I do not know why this happens. Any suggestions are welcome. I have done this before and never came across this error. I have also checked online and it looks like:
ostream& operator<< (ostream& out, char c );`
Upvotes: 2
Views: 1087
Reputation: 477010
The operator has to be a free function, because its first argument is not of the same type as your class. In general, when you overload a binary operator Foo
, the member function version only takes a single argument, and FOO(a, b)
means a.Foo(b)
.
Since a << b
would invoke a.operator<<(b)
, but a
is the stream, this is of no use for us.
So make a free function, or perhaps a free friend function. Having a public toString
member function can help:
class Foo {
public:
std::string toString() const;
// ...
};
std::ostream & operator<<(std::ostream & o, const Foo & x) {
return o << x.toString();
}
Upvotes: 3
Reputation: 81349
You are using the free form signature to define a member function. Member functions have an implicit this
argument, so in your case your member function attempt at overloading operator <<
would result in a function that takes 3 arguments: implicit this
, std::ostream&
os and BmvMessage const&
bm.
You can't define streaming operators as members, since the first argument needs to be of stream class. Instead, you define them as free functions, possibly friended if needed.
Upvotes: 1
Reputation: 363547
Take operator<<
outside the class, making it a free function. Make it a friend
of the class if it needs access to private
parts.
Upvotes: 3