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

C++ Error using a custom ifstream class with a variable as argument

本文关键字:自定义 ifstream 出错 参数 变量 C++      更新时间:2023-10-16

我正在使用自定义的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 它们,我将不胜感激

您可能需要替换:

plb_ifstream ifile(ostr.str());

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

获取 C 字符串等效项

你还没有编写一个plb_ifstream构造函数来接受一个std::string,例如你的std::ostringstream.str()返回的。 追加进一步.c_str()或添加构造函数。