如何将cin或ifstream对象作为参数函数传递

lad*_*kie 6 c++

我虽然这可以ifstream继承自从继承istream

string getFileContents(istream& file_contents)
{
    string result;

    string line;
    while (getline(file_contents, line))
        result += line + "\n";

    return result;
}
Run Code Online (Sandbox Code Playgroud)

然后我想这样调用这个函数:

ifstream file_input;
getFileContents(file_input);
...
getFileContents(cin);
Run Code Online (Sandbox Code Playgroud)

但是我在visual studio中遇到了这个错误:

'getFileContents':无法将参数1转换std::istreamstd::ifstream &

Mat*_*lia 7

它应该工作; 你确定你没有留下具有类型参数的错误原型ifstream &而不是istream &