我有以下代码:
namespace foo {
namespace bar {
class Baz {
protected:
void print(std::ostream&);
public:
friend std::ostream& operator<<(std::ostream& o, Baz& b) {
b.print(o);
return o;
}
}}}
然后在另一个文件中
Baz* b = getBaz();
LOG4CXX_INFO(logger, "Baz is " << *b);
我收到来自gcc的错误消息,并显示以下消息:
error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
似乎混淆是由于log4cxx中此重载的定义
// messagebuffer.h
template<class V>
std::basic_ostream<char>& operator<<(CharMessageBuffer& os, const V& val) {
return ((std::basic_ostream<char>&) os) << val;
}
我尝试通过以下方式修改代码:
//forward declaration
namespace foo {
namespace bar {
class Baz;
}
}
namespace std {
using foo::bar::Baz;
//implementation in cpp file
std::ostream& operator<<(std::ostream& o, Baz& b);
}
namespace foo {
namespace bar {
class Baz {
protected:
void print(std::ostream&);
public:
friend std::ostream& std::operator<<(std::ostream& o, Baz& b);
}}}
但是,代码再次失败并出现相同的错误。如何强制编译器使用自己的运营商版本?
答案 0 :(得分:2)
似乎您应该将Baz&
参数声明为const Baz&
,而print
方法也应该声明为const
。
namespace foo {
namespace bar {
class Baz {
protected:
void print(std::ostream&) const;
public:
friend std::ostream& operator<<(std::ostream& o, const Baz& b) {
b.print(o);
return o;
}
};
}}