我应该如何在 C++ 中做这样的事情?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string input_filename_ = "";
istream& input = (input_filename_ == "") ? cin : ifstream(input_filename_, ifstream::in);
我收到这个错误,不知道为什么。
E0330 "std::basic_istream<_Elem, _Traits>::basic_istream(std::basic_istream<_Elem, _Traits>::_Myt &&_Right) [with _Elem=char, _Traits=std::char_traits]" (declared at line 55 of "d:\Program Files\Visual Studio 2017\VC\Tools\MSVC\14.11.25503\include\istream") is inaccessible
最佳答案
您不能将临时变量绑定(bind)到您的非常量 引用。您必须创建一个真正的变量并绑定(bind)它:
ifstream ifs(input_filename, ifstream::in); // a real variable
istream& input = input_filename.empty() ? cin : ifs; // that should bind properly
通常我会做一些与此更相似的事情来确保用户提供了文件名并正确打开了文件:
std::ifstream ifs;
if(!file_name.empty()) // do we have a file name?
ifs.open(file_name); // try to open it
if(!ifs) // if we tried to open it but it failed
throw std::runtime_error(std::string(std::strerror(errno)) + ": " + file_name);
// only attach file to reference if user gave a file name
std::istream& in = file_name.empty() ? std::cin : ifs;
关于c++ - 基于条件的 Istream 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848297/