C++-函数范围内的函数声明
C++ - Function declarations inside function scopes?
不久前,我正在浏览C++11标准草案,发现了这个(见§8.3.6,第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)
}
这与函数的默认参数有关。令我印象深刻的是,函数声明出现在函数范围中。为什么?此功能的用途是什么?
虽然我不知道你能做到这一点,但我测试了它,它能工作。我想您可以使用它来转发稍后定义的声明函数,如下所示:
#include <iostream>
void f()
{
void g(); // forward declaration
g();
}
void g()
{
std::cout << "Hurray!" << std::endl;
}
int main()
{
f();
}
如果删除正向声明,程序将不会编译。因此,通过这种方式,您可以获得某种基于范围的前向声明可见性。
任何函数/变量声明都有其可见性和作用域。例如,如果在类中,则只有类成员才能看到它。如果在函数中,则在我们声明变量或函数之后,只有函数才能对它具有可见性。
我们通常在函数范围内使用数据结构。但编译器的语法规则适用于两者,因为函数本身有地址,因此可见性也适用于它。
相关文章:
- Visual Studio中的函数声明和函数定义问题
- 为什么函数声明中允许 const?
- 如果 x.h 仅由函数声明组成,为什么有必要在 x 中包含 x.h.cpp
- * 和 ** 在 C++ 函数声明中是什么意思?
- 构造函数/函数声明参数列表中的统一初始化
- 在将函数声明为友元时,尖括号的含义是什么?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 如何正确编写指针函数声明?
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 为什么要将函数声明和定义放在单独的文件中
- 为什么系统日志有两个不同的函数声明?
- 我如何获取数组的大小,以便我可以从函数声明所述数组
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- JavaScript 中的一等函数和 C++ 中的函数声明
- C++ 通过函数声明后初始化向量
- VS2017 #error: : snprintf 的宏定义与标准库函数声明冲突
- C++ 17 个友元函数声明和内联命名空间
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- 将派生类的构造函数声明为父类的友元
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明