像我这样的大多数 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.
//...
}
虽然一旦你知道错误就很明显了,但我想知道这种局部函数声明是否有任何合理的用途,除非你可以这样做——尤其是因为没有办法定义 这样的局部函数在同一个 block 中;你必须在别处定义它。
我认为 Java 风格的本地类是我经常使用的一个非常好的特性,尤其是匿名排序。甚至本地 C++ 类(可以具有内联定义的成员函数)也有一些用途。但是这个没有定义的局部函数声明对我来说似乎很尴尬。它只是一个 C-legacy 还是有一些我不知道的更深层次的用例?
编辑非信徒: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
科莫:
error: expression must be a modifiable lvalue
最佳答案
我能想到的唯一用途就是缩小函数声明的范围:
int main()
{
void doSomething();
doSomething();
return 0;
}
void otherFunc()
{
doSomething(); // ERROR, doSomething() not in scope
}
void doSomething()
{
...
}
当然,对此有更好的解决方案。如果你需要隐藏一个函数,你真的应该通过将函数移动到单独的模块中来重构你的代码,以便需要调用你想要隐藏的函数的函数都在同一个模块中。然后,您可以通过将其声明为静态(C 方式)或将其放入匿名命名空间(C++ 方式)来将该函数设为模块本地。
关于c++ - 局部函数声明有什么用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1034606/