gpt4 book ai didi

c++ - 我怎样才能使用我自己的 abc::endl;就像在 iostream 中一样

转载 作者:行者123 更新时间:2023-11-28 07:23:51 29 4
gpt4 key购买 nike

当我尝试自己的版本时,我得到了

error 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 命名空间内(但在类之外,然后我得到

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(); 返回日志;

最佳答案

std::endl是一个接受 std::ostream 的函数作为它的单一参数,ostream<<是一个重载,其类型为 std::endl .

为您的 log_stream 复制此行为, 覆盖 std::endl为此:

abc::log_stream& std::endl( abc::log_stream& log )
{
log.endl();
return log;
}

并覆盖 abc::log_stream::operator<<使用它:

abc::log_stream& abc::log_stream::operator<<( log_stream& (*pf)(log_stream&) )
{
return pf(*this);
}

如您所见,abc::log_stream::operator<< 的参数采用 std::endl 的类型作为参数。

另外,请注意 std::endl flushes the stream .因此,您应该考虑调用 fflush(fp_)abc::log::endl() .

关于c++ - 我怎样才能使用我自己的 abc::endl;就像在 iostream 中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19053556/

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