【问题标题】:How to initialize declared istringstream with string?如何用字符串初始化声明的 istringstream?
【发布时间】:2018-11-03 22:40:10
【问题描述】:

在 C++ 中,如何用字符串初始化已声明的 istringstream?

example.hpp

#include <sstream>
class example{
    private:
        istringstream _workingStream;
    public:
        example();
}

example.cpp

example::example(){
    this->_workingStream("exampletext");
}

错误

错误:不匹配调用“(std::istringstream {aka std::basic_istringstream}) (const char [8])”

【问题讨论】:

    标签: c++ getline istringstream


    【解决方案1】:

    要构造一个类成员,您需要使用class member initialization list。一旦进入构造函数的主体,所有类成员都已被构造,您所能做的就是分配给它们。要使用成员初始化列表,您需要将构造函数更改为

    example::example() : _workingStream("exampletext") {}
    

    【讨论】:

    • 发现在构造函数中也可以使用this-&gt;_workingStream.str("exampletext");
    • @Eugene - 一般来说,如果可能的话,最好在初始化列表中初始化类成员而不是构造函数主体。即使您不这样做,也需要先初始化对象,然后才能在构造函数主体中设置它,因此最好避免“初始化然后重置”循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2011-06-17
    相关资源
    最近更新 更多