c++中fstream指针的映射

map of fstream pointers in c++

本文关键字:映射 指针 fstream c++      更新时间:2023-10-16

我想有一个(int, fstream*)的映射,并使用一些函数修改它。我可以很容易地在main中修改它,但如果我想通过发送指针到fstream来使用它,我得到了这个编译器错误:错误C2440: '=':不能从'std::fstream'转换为'std::basic_fstream<_Elem,_Traits> *'

map<int, fstream*> m;
void func(fstream* f){
m[0] = *f; //compile error
}
int main( int argc, const char* argv[] )
{
fstream f("hi.txt");
func(&f); //error
m[0] = &f;   //work fine
f.close();
system("pause");
}

我怎样才能改变它?

不要在函数内部取消对指针的引用。

使用

void func(fstream* f){
  m[0] = f; //no more compile errors
}