问题描述
我正在经历,不久前又遇到了这个问题(第8.3.6页,第204页):
I was going through C++11 standard draft a while ago and came across this one (in §8.3.6, p. 204):
void g(int = 0, ...); // OK, ellipsis is not a parameter so it can follow
// a parameter with a default argument
void f(int, int);
void f(int, int = 7);
void h() {
f(3); // OK, calls f(3, 7)
void f(int = 1, int); // error: does not use default
// from surrounding scope
}
void m() {
void f(int, int); // has no defaults
f(4); // error: wrong number of arguments
void f(int, int = 5); // OK
f(4); // OK, calls f(4, 5);
void f(int, int = 5); // error: cannot redefine, even to
// same value
}
void n() {
f(6); // OK, calls f(6, 7)
}
函数的默认参数。让我感到震惊的是,函数声明出现在函数范围内。这是为什么?此功能是做什么用的?
This had to do with default arguments to functions. What struck me was the fact that function declarations appeared at the function scope. Why is that? What is this feature used for?
推荐答案
尽管我不知道您可以做到这一点,但我对其进行了测试,并且可以正常工作。我猜您可能会使用它来向前声明稍后定义的函数,如下所示:
Although I had no idea you can do this, I tested it and it works. I guess you may use it to forward-declare functions defined later, like below:
#include <iostream>
void f()
{
void g(); // forward declaration
g();
}
void g()
{
std::cout << "Hurray!" << std::endl;
}
int main()
{
f();
}
如果删除前向声明,则程序将无法编译。因此,通过这种方式,您可以具有某种基于范围的前向声明可见性。
If you remove the forward declaration, the program won't compile. So in this way you can have some kind of scope-based forward declaration visibility.
这篇关于C ++-函数范围内的函数声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!