다음은 아마도 여러분에게 매우 불쾌한 질문 일 것입니다 : 어떻게 (가능하다면) 함수에서 ifstream을 반환 할 수 있습니까?함수에서 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.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
나열된 것은 컴파일러 오류가 아니며 "메모"입니다. 실제 오류를보십시오. –