在做一些重构时,在类的成员函数中移动一些代码后,我得到了一个错误:
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());
}发布于 2016-03-12 21:25:23
如果你看到this std::ostream constructor reference,你会发现唯一的公共构造函数是一个接受指向std::streambuf对象的指针的构造函数,比如你的变量fileBuffer。
所以解决你的问题的一种方法是
std::filebuf fileBuffer;
std::ostream logStream(&fileBuffer);一个更好的解决方案是使用std::ofstream,如果你想输出到一个文件。
如果您想要一个更通用的解决方案,其中应该可以使用任何类型的输出流,那么重新设计为使用引用是一种可能的解决方案。
或者,你知道,试着找到一个现有的日志库,它已经为你处理了所有的事情。
https://stackoverflow.com/questions/35958114
复制相似问题