C++ 基本团队的问题
我在尝试编译代码时遇到以下错误:C++ 基本团队的问题,c++,C++,我在尝试编译代码时遇到以下错误: 1> c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/ostream: In constructor 'Log::Log(const char*)': 1>c:\mingw\bin\..\lib\gcc\mingw32\4.6.2\include\c++\ostream(363,7): error : 'std::basic_ostream<_CharT, _Traits>::basi
1> c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/ostream: In constructor 'Log::Log(const char*)':
1>c:\mingw\bin\..\lib\gcc\mingw32\4.6.2\include\c++\ostream(363,7): error : 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char, _Traits = std::char_traits<char>]' is protected
1>C:\Users\Adam\Documents\cs\cs176b\hw2\ftp\ftp\log.cpp(6,26): error : within this context
1>c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/ostream:在构造函数“Log::Log(const char*)”中:
1> c:\mingw\bin\..\lib\gcc\mingw32\4.6.2\include\c++\ostream(363,7):错误:“std::basic_ostream::basic_ostream()[with _CharT=char,_Traits=std::char_Traits]”受保护
1> C:\Users\Adam\Documents\cs\cs176b\hw2\ftp\ftp\log.cpp(6,26):错误:在此上下文中
不太清楚为什么,我没有自己编写ostream代码,我使用了这里建议的代码:
我的代码如下,如果需要,很乐意提供更多信息:
// 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;
}
//log.h
#包括
#包括
#ifndef日志_
#定义日志_
类日志
{
公众:
枚举模式{STDOUT,FILE};
//默认情况下需要
日志(const char*file=NULL);
~Log();
//写作方法
无效写入(字符*);
空写(std::string);
私人:
模式;
标准::streambuf*buf;
std::的流;
std::ostream out;
};
#恩迪夫
//log.cpp
#包括“log.h”
#包括
#包括
#包括
日志::日志(常量字符*文件)
{
如果(文件!=NULL)
{
打开(文件);
buf=of.rdbuf();
模式=文件;
}
其他的
{
buf=std::cout.rdbuf();
模式=标准输出;
}
//附加到输出
out.rdbuf(buf);
}
日志::~Log()
{
如果(模式==文件)
of.close();
}
void Log::write(std::string s)
{
超出大卫所说的范围:
ostream
只是输出流的“框架”,是输出流(抽象类)基本功能的定义。它不做任何事情,也没有实现
您是否尝试写入cout
也许?cout
是在iostream
中定义的,您不需要定义它,只需使用它!,这意味着它只能由其派生类调用,但不能由其封闭类调用
要修复此错误,请初始化成员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
std::ostream
具有受保护的默认构造函数而崩溃。你不能像那样实例化它。好吧,那么如果我以后想将更改为out
以使用我的代码中提供的文件流,它会工作吗?