返回随机数

时间:2017-03-01 05:38:50

标签: c++

以下代码:

#include <iostream>
using namespace std;
int test()
{
    cout<<"question \n";
    return 0;
}
int main(){
    cout<<test;
}

输出:     题     1

以下代码每次运行时都会给出1,但我希望输出为0。

然而,当我用test()替换测试时,我得到了预期的输出。不知道为什么会这样。如果背后有任何规则,请建议并发表评论。

2 个答案:

答案 0 :(得分:2)

C ++总是要求您使用括号来调用函数。如果省略它们,它会认为您想知道函数的地址而不是调用它。然后将该地址视为(truthy)布尔值并输出为1.此警告(来自gcc -Wall)解释得很好:

x.cpp: In function ‘int main()’:
x.cpp:9:11: warning: the address of ‘int test()’ will always evaluate as ‘true’ [-Waddress]
     cout<<test;
           ^

答案 1 :(得分:0)

std::cout << test;

输出1因为test是一个函数指针,它将被std::cout转换为bool。

相关问题