Mer*_*sud 32 c++ ternary-operator operator-precedence
我正在解决有关主教在棋盘上移动的问题。在代码的某一时刻,我有以下语句:
std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
这将产生以下错误:
Run Code Online (Sandbox Code Playgroud)error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'
但是,我通过在代码中包含一个附加变量来立即修复此错误:
error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'
三元运算符如何工作,以及如何确定其返回类型(如编译器称为<unresolved overloaded function type>)?
Nat*_*ica 65
这与返回类型的推导方式以及运算符优先级无关。当你有
std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
不是
std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
因为?:它的优先级低于<<。这意味着您实际拥有的是
(std::cout << (abs(c2-c1) == abs(r2-r1))) ? 1 : (2 << std::endl);
这就是为什么您会收到有关的错误的原因<unresolved overloaded function type>。只需使用括号
std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
这样你就可以了
小智 11
您必须在三元运算符后加上括号:
std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
如果不是,则<<操作员转到,2并给出错误,因为它没有这样的重载功能。
发生这种情况是因为按位左移运算符(<<)的优先级高于三元运算符。您可以在C ++参考的本页中看到运算符的完整列表及其优先级。
由于运算符的优先级,该行被视为:
(std::cout << (abs(c2-c1) == abs(r2-r1))) ? 1 : (2 << std::endl);
更改为
std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
//           ^----------------------------------^
//           Surrounding parentheses
当可视化解析顺序时,很容易看到错误:
std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
\_______/                                                      <--- #1
             \________________________/   V   \~~~~error~~~/   <--- #2
             \_____________________________________________/   <--- #3
\__________________________________________________________/   <--- #4
\___________________________________________________________/  <--- #5
| 归档时间: | 
 | 
| 查看次数: | 3882 次 | 
| 最近记录: |