【问题标题】:C++ How to initialize a std::istream* although constructor is protectedC ++如何初始化std :: istream *尽管构造函数受到保护
【发布时间】:2013-08-28 22:09:12
【问题描述】:

我想使用带有流成员的类。

我的代码是这样的:

//! pushes a Source and InputFilters into a filtering_istream
class FilterChain {
public:
    //! create an empty FilterChain
    FilterChain(){
        init();
    }

private:
    //! the stream to connect Source and InputFilters together
    io::filtering_istream* m_filteringStream;
    //! stream to use by other classes
    std::istream* m_stream;

    void init(){
        std::streambuf* streamBuffer = m_filteringStream->rdbuf();
        m_stream->rdbuf(streamBuffer);
    }
};

我收到一条错误消息,表明 std::basic_istream 构造函数受到保护:

/usr/include/c++/4.8.1/istream:在成员函数`void FilterChain::init()'中: /usr/include/c++/4.8.1/istream:606:7: 错误:`std::basic_istream<_chart _traits>::basic_istream() [with _CharT = char; _Traits = std::char_traits]' 受保护

我也尝试了流引用,但这导致了同样的错误。任何想法如何解决这个问题?

编辑 1:

谢谢,我用这样的新 init() 修复了它:

void init(){
        std::streambuf* streamBuffer = m_filteringStream->rdbuf();
        m_stream = new std::istream(streamBuffer);
    }

【问题讨论】:

  • 专业提示:(a) 包含实际触发问题的代码。 (b) 在发布编译器错误之前切换到 en_US 语言环境
  • 我希望你将这些指针分配到某个地方。
  • @JoachimPileborg 编译器会为你分配指针......现在,程序员的工作是正确初始化它们:/
  • 我不会法语或其他任何语言:P
  • @P0W 我为你翻译了德语。

标签: c++ stream


【解决方案1】:

您显示的代码实际上根本不包含问题。

问题是您试图在某处(不在您的问题代码中)默认构造一个 istream 对象。

你需要至少一个缓冲区来初始化它:

std::filebuf  m_dummy;
std::istream  m_stream(&dummy);

现在,您可以像以前一样重新分配 rdbuf。另见,例如How can I switch between fstream files without closing them (Simultaneous output files) - C++

更新 正如 Dietmar 刚刚确认的那样,您可以将 nullptr 传递给 streambuf* 参数:

std::istream  m_stream(nullptr);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2020-05-05
    • 1970-01-01
    • 2013-08-04
    • 2013-10-14
    • 2011-05-30
    • 2022-01-22
    相关资源
    最近更新 更多