sam*_*kpo 7 c++ compilation parentheses
我正在看一个朋友寄给我的一些代码,他说:"它编译,但不起作用".我看到他使用没有括号的函数,如下所示:
void foo(){
cout<< "Hello world\n";
}
int main(){
foo; //function without parentheses
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我说的第一个是"使用括号,你必须".然后我测试了那个代码 - 它确实编译了,但是当执行时不起作用(没有显示"Hello world").
那么,为什么要编译(编译器GCC 4.7完全没有警告),但不起作用?
Bo *_*son 12
如果您将警告级别设置得足够高,它肯定会发出警告.
函数名称的计算结果是函数的地址,是一个合法的表达式.通常它保存在函数指针中,
void (*fptr)() = foo;
Run Code Online (Sandbox Code Playgroud)
但这不是必需的.
CB *_*ley 11
您需要提高您使用的警告级别.foo;是一个有效的表达式语句(函数的名称转换为指向指定函数的指针),但它没有任何效果.
我经常使用-std=c++98 -Wall -Wextra -pedantic哪个给出:
<stdin>: In function 'void foo()':
<stdin>:2: error: 'cout' was not declared in this scope
<stdin>: In function 'int main()':
<stdin>:6: warning: statement is a reference, not call, to function 'foo'
<stdin>:6: warning: statement has no effect
Run Code Online (Sandbox Code Playgroud)