我目前正在实现一个基于文本文件的测试UI,它将从文本文件中(逐行(获取模拟的用户输入来模拟真实的用户输入,而不是使用std::cin
。
当我尝试将std::cin
传递到std::ifstream
参数时,就会出现问题;无论是通过引用还是按值,问题仍然存在。
功能:
void ZoinkersEngine::displayMainMenu(User& currentUser, std::ifstream& in) {
//need a function to check the role level of the user here
//DEMO (Mock-up) of Menu
std::string option = "";
do {
std::cout << std::string(40, 'n');
std::cout << "Successfully logged in...nnn";
std::cout << "Main Menu:n";
std::cout << "[0] Order Plann";
std::cout << "[1] Generate Plannn";
std::cout << "Please input number of selected option: ";
// std::cin >> option;
in >> option;
if (option == "0") {
currentUser.calculateExhibitFav(zoinkersDirectory);
currentUser.orderPlan(zoinkersDirectory);
}
else if (option == "1") {
currentUser.calculateExhibitFav(zoinkersDirectory);
currentUser.generatePlan(zoinkersDirectory);
}
else if (option == "cancel" || option == "Cancel") {
break;
}
} while (option != "cancel" || option != "Cancel");}
调用函数:
engine.displayMainMenu(currentUser, std::cin);
错误:
cannot convert argument 2 from 'std::istream' to 'std::ifstream'
我无法弄清楚这一点;据我所知ifstream
是从istream
基类派生的,因此编译器应该能够强制转换它。
编辑#1:当前的IDE是Visual Studios 2017;答案也必须在g++上编译并在Linux上工作。
没有隐式向下转换。 如果您希望函数采用输入流,那么它应该具有签名
void ZoinkersEngine::displayMainMenu(User& currentUser, std::istream& in)
^ ^
| reference here
istream, not ifstream
现在,您可以将任何istream
或派生自的流传递给它。
这是必要的,因为
- 如果流是左值,则无法按值传递流,因为流不可复制 仅当基类最初是派生类
- 时,才能从基类强制转换到派生类。 这也只能通过指针完成,否则派生到基类的转换将切片,并且您将丢失派生类部分