如何确定三元运算符的返回类型?

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<<'
Run Code Online (Sandbox Code Playgroud)

但是,我通过在代码中包含一个附加变量来立即修复此错误:

error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'
Run Code Online (Sandbox Code Playgroud)

三元运算符如何工作,以及如何确定其返回类型(如编译器称为<unresolved overloaded function type>)?

Nat*_*ica 65

这与返回类型的推导方式以及运算符优先级无关。当你有

std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
Run Code Online (Sandbox Code Playgroud)

不是

std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
Run Code Online (Sandbox Code Playgroud)

因为?:它的优先级低于<<。这意味着您实际拥有的是

(std::cout << (abs(c2-c1) == abs(r2-r1))) ? 1 : (2 << std::endl);
Run Code Online (Sandbox Code Playgroud)

这就是为什么您会收到有关的错误的原因<unresolved overloaded function type>。只需使用括号

std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
Run Code Online (Sandbox Code Playgroud)

这样你就可以了

  • @MerajalMaksud差不多了,但是不完全是。它试图编译`2 &lt;&lt; std :: endl`并失败。 (4认同)
  • 原始代码实际上被解析为`(std :: cout &lt;&lt;(abs(c2-c1)== abs(r2-r1)))吗?1:(2 &lt;&lt; std :: endl);`“幸运的是”,iostream可以转换为布尔表达式,即,第一部分不会引起错误(只是意外的行为)。 (2认同)

小智 11

您必须在三元运算符后加上括号:

std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
Run Code Online (Sandbox Code Playgroud)

如果不是,则<<操作员转到,2并给出错误,因为它没有这样的重载功能。

发生这种情况是因为按位左移运算符(<<)的优先级高于三元运算符。您可以在C ++参考的本页中看到运算符的完整列表及其优先级。


R S*_*ahu 8

由于运算符的优先级,该行被视为:

(std::cout << (abs(c2-c1) == abs(r2-r1))) ? 1 : (2 << std::endl);
Run Code Online (Sandbox Code Playgroud)

更改为

std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
//           ^----------------------------------^
//           Surrounding parentheses
Run Code Online (Sandbox Code Playgroud)


ruo*_*ola 5

当可视化解析顺序时,很容易看到错误:

std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
\_______/                                                      <--- #1
             \________________________/   V   \~~~~error~~~/   <--- #2
             \_____________________________________________/   <--- #3
\__________________________________________________________/   <--- #4
\___________________________________________________________/  <--- #5
Run Code Online (Sandbox Code Playgroud)