将ifstream对象传递给需要istream类型的函数

时间:2012-10-12 11:09:53

标签: c++ inheritance ifstream istream

我有这个功能

void StrType::saveString(bool skip, InType charsAllowed, std::istream& inStream)
{ //something cool 
};

和这两个

void StrType::getString(bool skip, InType charsAllowed)
{
    saveString(skip, charsAllowed, std::cin);
}
void StrType::getStringFile(bool skip, InType charsAllowed,  std::ifstream& inFile)
{
    saveString(skip, charsAllowed, inFile);
}

你能告诉我为什么编译器抱怨

strtype.cpp: In member function ‘void StrType::getStringFile(bool, InType, std::ifstream&)’:
strtype.cpp:42:39: error: no matching function for call to ‘StrType::saveString(bool&, InType&, std::ifstream&)’
strtype.cpp:42:39: note: candidate is:
strtype.cpp:9:6: note: void StrType::saveString(bool, InType, std::istream&)
strtype.cpp:9:6: note:   no known conversion for argument 3 from ‘std::ifstream {aka std::basic_ifstream<char>}’ to ‘std::istream& {aka std::basic_istream<char>&}’

因为ifstream类是从istream继承的吗?或者我错了吗?

1 个答案:

答案 0 :(得分:8)

我认为最可能的原因是缺少<fstream>头文件。如果你所包含的只是<iosfwd>,那么编译器就不会知道ifstream继承自istream