gpt4 book ai didi

c++ - basic_ostream 的问题

转载 作者:行者123 更新时间:2023-11-28 03:23:32 24 4
gpt4 key购买 nike

我在尝试编译我的代码时遇到此错误:

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

不太清楚为什么,我没有制作我自己使用的 ostream 代码,我使用了这里建议的代码:Proper way to create ostream to file or 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() constructor is protected ,这意味着它只能由其派生类调用,而不能由其封闭类调用。

修复错误初始化成员 out

std::ostream 的唯一公共(public)构造函数接受 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 而崩溃。

关于c++ - basic_ostream 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14782809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com