在 ifstream 预期的地方传入 fstream

Alc*_*ott 4 c++ casting

void foo(ifstream &ifs)
{
    //do something
}

int main()
{
    fstream fs("a.txt", fstream::in);
    foo(fs); //error, can't compile
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不能编译,好像我不能ifstream &fstream对象初始化一个?如果我这样做怎么办:

foo(static_cast<ifstream>(fs)); 
Run Code Online (Sandbox Code Playgroud)

或者

foo(dynamic_cast<ifstream>(fs)); 
Run Code Online (Sandbox Code Playgroud)

nob*_*bar 5

可能您希望 foo() 接受 istream。如评论中所示,这是 ifstream 和 fstream 的基本类型。

void foo( istream & is )
Run Code Online (Sandbox Code Playgroud)

在 cplusplus.com 上有关于这些类的很好的参考: