使用带有变量作为参数的自定义 ifstream class 的 C++ 错误

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

我正在使用自定义 ifstream class

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() 或添加一个构造函数。