为什么我不能将 cin/cout 放入函数中并从 main() 调用该函数

Why I can not put cin/cout in a function and call that function from main()

int main(){
    ifstream in;
    in = open_file();
    return 0;
}
我想将 in/output 封装到一个函数中并从 main 调用该函数,但是编译器在我这样做后显示了一个奇怪的错误
Description Resource    Path    Location    Type
‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const   std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’ is private  Standford.Programming       line 802, external location: /usr/include/c++/4.8/streambuf C/C++ Problem
ifstream open_file(){
    ifstream in;
    string filename;
    cout << "Plean Enter File Name: ";
    cin >> filename;
    in.open(filename.c_str());
    while(true){
        if (in.fail()){
            cout << "Plean Enter File Name Again: ";
            cin >> filename;
            in.clear();
            in.open(filename.c_str());
        }
        else
            break;
    }
    return in;
}
int main(){
    ifstream in;
    in = open_file();
    return 0;
}
从主程序调用它
Description Resource    Path    Location    Type
‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const   std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’ is private  Standford.Programming       line 802, external location: /usr/include/c++/4.8/streambuf C/C++ Problem
int main(){
    ifstream in;
    in = open_file();
    return 0;
}
int main(){
    ifstream in;
    in = open_file();
    return 0;
}
错误(7 个错误)
Description Resource    Path    Location    Type
‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const   std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’ is private  Standford.Programming       line 802, external location: /usr/include/c++/4.8/streambuf C/C++ Problem
Description Resource    Path    Location    Type
‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const   std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’ is private  Standford.Programming       line 802, external location: /usr/include/c++/4.8/streambuf C/C++ Problem

编译器错误并不奇怪,因为无法复制,所以它就出现了。函数 open_file returns 一个 ifstream 对象 value 不受支持。

ifstream open_file()
{
    ifstream in;

    // snip

    return in; // return the stream by value requires a copy.
}

一个选项是将对流的引用作为参数传递给 open_file 函数。这将允许 open_file 函数处理打开文件以及任何函数调用它 read/write from/to 文件的能力。下面的代码应该让你回到正轨...

bool open_file(ifstream& in)
{
    string filename;
    cout << "Plean Enter File Name: ";
    cin >> filename;
    in.open(filename.c_str());

    // [snipped code].
    return in.is_open();
}

int main()
{
    ifstream in;
    if(open_file(in))
    {
        // do something if the file is opened
    }
    return 0;
}

std::ifstream 不可复制,但对于 C++11,它是可移动的,因此如果您在启用 c++11 的情况下进行编译(-std=c++11 for gcc/clang),您的代码应该编译。