流定义出错
Error with ostream definition
进行一些重构时,在类的成员函数中移动一些代码后出现错误:
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
如果要输出到文件。
如果你想要一个更通用的解决方案,其中应该可以使用任何类型的输出流,那么重新设计以使用引用是一个可能的解决方案。
或者,你知道,尝试找到一个现有的日志记录库,它已经为您处理了所有内容。
相关文章:
- 在定义的函数中使用常量时出错
- 在头文件中定义变量不会出错
- TraciMobility::getExternalId 将自定义模块添加到示例中时出错Veins_Inet (Omne
- PCL 出错:体系结构x86_64 @pcl的未定义符号
- 从 ParaView 构建自定义 Qt 应用程序示例时出错
- 在f2c.h文件中定义min()max()宏时出错
- 从 Arduino 中的自定义C++库构造对象时出错
- 包含适当的标头时,实现文件中的多个定义出错
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- '未定义对..'的引用;将APP_STL从gnustl_static切换到c++_shared后出错
- 使用静态变量未解析的外部符号/未定义的引用时出错
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- 在类外部定义显式运算符 bool() 时出错
- C++ Linux 加载共享库时出错“未定义的符号:pthread_create”
- 模板化函数重载和类外定义时出错
- 链接webrtc本机时出错,因为未定义对具有std::string的方法的引用
- 使用自定义类集时出错
- 尝试定义派生自抽象类的类类型的对象时出错
- 编译共享对象时出错:未检测到C++类定义
- 在 CPLEX 中使用 IloRange 定义约束时出错 (c++)