流定义出错

Error with ostream definition

本文关键字:出错 定义      更新时间:2023-10-16

进行一些重构时,在类的成员函数中移动一些代码后出现错误:

std::ostream  logStream;         //  <-- error
std::filebuf  fileBuffer;
// Send the output either to cout or to a file
if(sendToCout) {
    logStream.rdbuf(std::cout.rdbuf());
}
else {
    fileBuffer.open("out.txt", std::ios_base::out | std::ofstream::app);
    logStream.rdbuf(&fileBuffer);
}
logStream << "abcd..." << std::endl;

这是编译器错误消息:

file.cpp:417: error: calling a protected constructor of class 'std::__1::basic_ostream<char>'
        std::ostream  logStream;
                      ^

这可能是一个解决方案吗?

std::filebuf  fileBuffer;
std::ostream  logStream(&fileBuffer);
...
if(sendToCout) {
    logStream.rdbuf(std::cout.rdbuf());
}
例如,

如果您看到这个std::ostream构造函数引用,您将看到唯一的公共构造函数是指向std::streambuf对象的指针,例如您的变量 fileBuffer .

所以解决问题的一种方法是

std::filebuf  fileBuffer;
std::ostream  logStream(&fileBuffer);

更好的解决方案是使用 std::ofstream 如果要输出到文件。

如果你想要一个更通用的解决方案,其中应该可以使用任何类型的输出流,那么重新设计以使用引用是一个可能的解决方案。

或者,你知道,尝试找到一个现有的日志记录库,它已经为您处理了所有内容。