我有一些现有代码可以在 Visual Studio 2010 中正常编译,但在 Visual Studio 2013 中会出错。代码只是从 istringstream 中提取一个字符串并检查转换是否成功:
bool okFlag = false;
istringstream s;
string myStr;
<snip>
okFlag = s >> myStr;
错误是:
error C2440: '=' : cannot convert from 'std::basic_istream<char,std::char_traits<char>>' to 'bool'
我猜想在 C++11 中,转换的返回类型不是 bool。正确的做法是什么?是否有可能同时满足 VS2010 和 VS2013 的代码?
最佳答案
在 C++11 中 basic_ios::operator bool
是 explicit
,而 C++03 用户定义的到 void *
的转换可隐式转换为 bool
。要修复您的代码,您需要显式转换结果。
okFlag = static_cast<bool>(s >> myStr);
请注意,显式 bool
转换运算符在需要 bool 结果的上下文中仍将隐式转换为 bool
,例如 if< 中的条件表达式
声明。这就是为什么下面的代码无需添加强制转换就可以编译的原因。
if(s >> myStr) { // here operator bool() implicitly converts to bool
// extraction succeeded
}
关于c++ - 如何修复 istringstream 编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22330765/