basic_stream出现问题
Issues with basic_ostream
我在尝试编译代码时遇到此错误:
1> c:mingwbin../lib/gcc/mingw32/4.6.2/include/c++/ostream: In constructor 'Log::Log(const char*)':
1>c:mingwbin..libgccmingw324.6.2includec++ostream(363,7): error : 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char, _Traits = std::char_traits<char>]' is protected
1>C:UsersAdamDocumentscscs176bhw2ftpftplog.cpp(6,26): error : within this context
不知道为什么,我没有自己制作我正在使用的ostream代码,我使用了这里的建议:创建ostream到文件或cout 的正确方法
我的代码如下,如果需要,很乐意提供更多信息:
// log.h
#include <string>
#include <fstream>
#ifndef LOG_H_
#define LOG_H_
class Log
{
public:
enum Mode { STDOUT, FILE };
// Needed by default
Log(const char *file = NULL);
~Log();
// Writing methods
void write(char *);
void write(std::string);
private:
Mode mode;
std::streambuf *buf;
std::ofstream of;
std::ostream out;
};
#endif
// log.cpp
#include "log.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
Log::Log(const char *file)
{
if (file != NULL)
{
of.open(file);
buf = of.rdbuf();
mode = FILE;
}
else
{
buf = std::cout.rdbuf();
mode = STDOUT;
}
// Attach to out
out.rdbuf(buf);
}
Log::~Log()
{
if (mode == FILE)
of.close();
}
void Log::write(std::string s)
{
out << s << std::endl;
}
void Log::write(char *s)
{
out << s << std::endl;
}
std::ostream::ostream()
构造函数受到保护,这意味着它只能由其派生类调用,但不能由其封闭类调用。
若要修复错误,请初始化成员out
。
std::ostream
的唯一公共构造函数接受std::streambuf*
,例如:
Log::Log(const char *file)
: out(std::cout.rdbuf())
// ...
请注意,使用std::cout.rdbuf()
中的缓冲区初始化std::ostream
是安全的,因为析构函数std::ostream::~ostream()
不会解除分配其std::streambuf*
成员。
或者,它可以用NULL
/nullptr
进行初始化。在这种情况下,请注意不要向流中输出任何内容,因为它会尝试取消引用NULL
,从而导致未定义的行为,很可能只是与SIGSEGV
一起崩溃。
大卫所说的话的扩展:
ostream
只是输出流的"框架",是输出流(抽象类)基本功能的定义。它什么也不做,也没有实施。
你有没有试着写信给cout
?cout
是在iostream
中定义的,您不需要定义它,只需使用它!
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题