gpt4 book ai didi

c++ - 自定义重载运算符 << 与 log4cxx

转载 作者:太空狗 更新时间:2023-10-29 21:32:33 26 4
gpt4 key购买 nike

我有以下代码:

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);
}}}

但是代码再次失败并出现相同的错误。如何强制编译器使用我自己的运算符版本?

最佳答案

看来你应该将 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;
}
};

}}

关于c++ - 自定义重载运算符 << 与 log4cxx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54781549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com