我有一些具有以下功能的 Logging::Logger
类:
template<typename T>
const Logger& Logger::operator<<(const T& in) const {
// ...
return *this;
}
const Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&)) {
// ...
return *this;
}
以及以下代码:
loggerInstance << "ID: " << 5 << endl;
虽然所有操作符似乎都已实现,但我收到以下错误:
error C2678: binary '<<': no operator found which takes a left-hand operand of type 'const Logging::Logger' (or there is no acceptable conversion)
当然,没有 endl
一切正常。
我看过以下答案:
std::endl is of unknown type when overloading operator<<
我错过了什么?
最佳答案
因为您的重载运算符返回一个 const Logger &
, 因此它们必须是 const
类方法,以便您能够将它们链接在一起:
const Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&)) const
但是,最好不要 const
类成员,并返回一个 Logger &
,而是:
template<typename T> Logger& Logger::operator<<(const T& in)
Logger& Logger::operator<<(std::ostream& (*os)(std::ostream&))
这大概是因为 operator<<
将修改 Logger
例如,以某种方式。如果没有,您可以使用 const
对象和方法,在这里。
关于c++ - std::endl 不适用于重载的运算符<<,尽管实现了专用的非模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809116/