传入 fstream,但需要 ifstream。

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

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

上述代码无法编译,看起来我不能用一个 fstream 对象初始化一个 ifstream &?如果我这样做会怎样:
foo(static_cast<ifstream>(fs)); 

或者

foo(dynamic_cast<ifstream>(fs)); 

1
首先,它们是不相关的类型。 - Oliver Charlesworth
3
ifstream并不是继承于fstream。虽然fstream和ifstream都继承自istream,但除此之外它们没有关联,就像Oli所说的那样。 - Corbin
@Corbin,天啊,我以为ifstreamofstream是从fstream派生出来的。 - Alcott
1
是的,这有点奇怪,但我猜他们决定使用fstream而不是iofstream :)。 - Corbin
1个回答

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接