c++ - 如何修复 istringstream 编译器错误?

标签 c++ visual-studio-2010 c++11 visual-studio-2013

我有一些现有代码可以在 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 boolexplicit,而 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/

相关文章:

c++ - vector 的 push_back 错误背后的原因是什么

c++ - c++中存储的非标准函数的声明在哪里?

c++ - gcc vector 扩展中的未对齐加载/存储

C++默认构造函数无法初始化公共(public)变量?

visual-studio-2010 - 模拟器不会在 Visual Studio 2010 中显示

c++ - 为什么 decltype 不能与重载函数一起使用?

c++ - 有没有办法抑制 C++ 名称修改?

c++ - 支持初始化 std::map 成员编译器错误

c++ - 编译错误。正确的代码和输出是什么?

javascript - 使用 jquery 读取给定 url 的来源