大多数像我这样的C++程序员在某个时刻都犯过以下错误:
class C { /*...*/ };
int main() {
C c(); // declares a function c taking no arguments returning a C,
// not, as intended by most, an object c of type C initialized
// using the default constructor.
c.foo(); // compiler complains here.
//...
}
现在当你知道错误后,它似乎非常显而易见。但我想知道除了你可以这样做之外,是否有任何明智的用途来声明这种本地函数 - 特别是因为没有办法在同一块中定义这样的本地函数; 你必须在其他地方定义它。
我认为Java风格的本地类是一个相当不错的功能,我经常使用它们,特别是匿名类型。即使是本地C++类(可以具有内联定义的成员函数)也有一些用处。但是这种未定义的本地函数声明对我来说似乎非常尴尬。它只是C语言遗留问题吗?还是有某些更深层次的用例我不知道?
编辑:对于那些不信的人:C c()
不是函数指针声明。
这个程序
int main()
{
void g();
cout << "Hello ";
g();
return 0;
}
void g()
{
cout << "world." << endl;
}
输出 Hello world.
这个程序。
void fun()
{
cout << "world." << endl;
}
int main()
{
void g();
g = fun;
cout << "Hello ";
g();
return 0;
}
编译不通过。gcc 报错:
error: cannot convert 'void ()()' to 'void ()()' in assignment
Comeau 报错:
error: expression must be a modifiable lvalue
void(g)()
声明函数,当处理函数指针时需要使用它:void * g()
是返回void*
的函数,而void(* g)()
是指向类型为void()()
的函数的指针,即不带参数且不返回任何内容的函数。 - Tobias