为什么“计算一个函数而不调用它(不是 f() 而是 f;)。始终打印 1?”
在此代码中,该代码尝试在不使用括号的情况下“调用”名为 pr 的函数。然而,这实际上并不是调用该函数。相反,它将函数指针传递给 cout 函数。当函数指针隐式转换为 bool 值时,其计算结果为 true。由于 true 相当于 C 中的 1,因此输出始终为 1。
为了澄清,所提供代码中的以下几行并未调用 pr 函数:
<code class="cpp">pr; cout << pr; // output: 1 cout << *pr; // output: 1 (dereferencing the function pointer, which is still true) cout << ≺ // output: 1 (address of the function, which is a non-zero value)</code>
要真正调用对于 pr 函数,您需要使用像 pr() 这样的括号。
此行为源于函数指针可以隐式转换为 bool 的事实。在 C 11 中,可以重载运算符
以上是为什么使用不带括号的函数指针时'cout”打印'1”?的详细内容。更多信息请关注PHP中文网其他相关文章!