代码之家  ›  专栏  ›  技术社区  ›  Fowaz Ikram

C++使用带有变量作为参数的自定义ifstream类时出错

  •  -1
  • Fowaz Ikram  · 技术社区  · 11 年前

    我正在使用自定义ifstream类

    class plb_ifstream : public Parallel_istream {
    public:
    plb_ifstream();
    explicit plb_ifstream(const char* filename,
                          std::istream::openmode mode = std::ostream::in );
    ~plb_ifstream();
    virtual std::istream& getOriginalStream();
    
    bool is_open();
    void open(const char* filename, std::istream::openmode mode = std::ostream::in);
    void close();
    bool good();
    private:
    plb_ifstream(plb_ifstream const& rhs);
    plb_ifstream& operator=(plb_ifstream const& rhs);
    private:
    DevNullBuffer devNullBuffer;
    std::istream  devNullStream;
    std::ifstream *original;
    

    };

    这对于单个文件(如

    plb_ifstream ifile("geometry.dat");
    

    然而,当我尝试在参数中使用变量(在for循环中)时

    for(plint num=1; num<4; num++)
    {
        std::ostringstream ostr;
        ostr <<num<<".dat";
        std::string var = ostr.str();
    
        pcout <<"Reading geometry.."<<endl;
        plb_ifstream ifile(ostr.str());
        ifile >> boolMask;
        pcout<<"done..."<<endl;}
    

    我收到以下错误

    error: no matching function for call to ‘plb::plb_ifstream::plb_ifstream(std::basic_ostringstream<char>::__string_type)’|
    note: candidates are:|
    note: plb::plb_ifstream::plb_ifstream(const plb::plb_ifstream&)|
    note: no known conversion for argument 1 from ‘std::basic_ostringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘const plb::plb_ifstream&’|
    note: plb::plb_ifstream::plb_ifstream(const char*, std::ios_base::openmode)|
    note:   no known conversion for argument 1 from ‘std::basic_ostringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘const char*’|
    note: plb::plb_ifstream::plb_ifstream()|
    note:   candidate expects 0 arguments, 1 provided|
    

    我确实找到了一些其他解决方案,但它们没有使用ifstream。如果只使用ifstream,我会很感激你的帮助

    2 回复  |  直到 11 年前
        1
  •  2
  •   Jacob Seleznev    11 年前

    您可能需要更换:

    plb_ifstream ifile(ostr.str());
    

    具有

    plb_ifstream ifile(ostr.str().c_str());
    

    要获得C字符串等效值

        2
  •  1
  •   Tony Delroy    11 年前

    你还没有写 plb_ifstream 构造函数 std::string 比如你的 std::ostringstream 的 .str() 。追加一个 .c_str() 或添加构造函数。