【发布时间】:2013-09-27 14:41:27
【问题描述】:
当我尝试自己的版本时,我得到了
错误 C2039:“endl”:不是“abc”的成员 错误 C2065: 'endl' : 未声明的标识符
这是下面的代码。
#include <iostream>
#include <stdio.h>
//assume this class uses some proprietary logging system. I just use the wrap the C
//output functions here but assume is a corporate log system
namespace abc {
class log_stream
{
public:
log_stream(const char* filename) {
fp_ = fopen(filename, "w");
}
log_stream& operator<<(short val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(unsigned short val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(int val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(unsigned int val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(long val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(unsigned long val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(const char* val) { if (fp_) { output_string(val); } return *this; }
inline log_stream& endl(log_stream& os) { return os.endl(); }
//etc
log_stream& endl() {
if(fp_)
fputc('\n', fp_);
return *this;
}
private:
void output_int(long v) { fprintf(fp_, "%d", v); }
void output_string(const char* s) { fprintf(fp_, "%s", s); }
FILE* fp_;
};
} //namespace abc
int main() {
abc::log_stream logger("myfile.txt");
//error C2039: 'endl' : is not a member of 'abc', error C2065: 'endl' : undeclared identifier
logger << "number " << 3 << abc::endl;
return 0;
}
更新:
如果我添加
inline log_stream& endl(log_stream& os) { return os.endl(); }
在 abc 命名空间内(但在类之外,然后我得到 p>
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'abc::log_stream' (or there is no acceptable conversion)
哪个更接近(我认为)解决,但还没有。
更新2。
嗯,那是毛茸茸的!这是我为任何做类似事情的人解决问题的方法。谢谢朱利安。
将这些添加到类中:
~log_stream() { if(fp_) fclose(fp_); }
// this is the main one I was missing
abc::log_stream& abc::log_stream::operator<<( log_stream& (*pf)(log_stream&) )
{
return pf(*this);
}
然后课外:
abc::log_stream& endl(abc::log_stream& 日志) { 日志.endl(); 返回日志; }
【问题讨论】:
-
我在
log_stream类中看到了一个endl成员函数。我在abc命名空间中没有看到声明为顶级的endl实体。我错过了什么吗? -
有点跑题了——你真的想要一个有自己实现的日志流吗?看看marcoarena.wordpress.com/2013/09/13/…
-
更新后:现在看看约翰的回答。