operator overload <<
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 );`
Take operator<<
outside the class, making it a free function. Make it a friend
of the class if it needs access to private
parts.
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();
}
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.
链接地址: http://www.djcxy.com/p/73102.html上一篇: 类c ++中的运算符重载函数
下一篇: 运算符过载<<