这里有一个可能非常新手的问题:如何(如果可能的话)从函数中返回一个 ifstream?
基本上,我需要从用户那里获取数据库的文件名,如果该文件名对应的数据库不存在,则需要为用户创建该文件。我知道如何做到这一点,但是只能通过要求用户在创建文件后重新启动程序来实现。如果可能的话,我想避免给用户带来这种不便,但是下面的函数无法在gcc中编译:
ifstream getFile() {
string fileName;
cout << "Please enter in the name of the file you'd like to open: ";
cin >> fileName;
ifstream first(fileName.c_str());
if(first.fail()) {
cout << "File " << fileName << " not found.\n";
first.close();
ofstream second(fileName.c_str());
cout << "File created.\n";
second.close();
ifstream third(fileName.c_str());
return third; //compiler error here
}
else
return first;
}
编辑:抱歉,忘记告诉您编译错误出现在哪里以及是什么:
main.cpp:45: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here
编辑:我根据Remus的建议将函数更改为返回指针,并将main()中的行更改为“ifstream database = *getFile()”;现在我再次遇到此错误,但这次出现在main()中的一行:
main.cpp:27: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here