Scope
C++ 的作用域是对C中的作用域的一种扩展与细化?
标准:C99 6.2.1 与 C++0x 3.3
C | C++ | 备注 |
blockscope | localscope | |
functionscope | functionscope | |
functionprototype scope | function prototypescope | |
file (global)scope | global namespacescope | |
namespacescope | ||
classscope | ||
enumerationscope | C++0x | |
template parameterscope | C++0x |
function scope
标签(Labels)是唯一一类拥有function scope的名字。可以在它所出现的函数中的任何位置被使用(通过goto语句)。
function prototype scope
函数原型中声明的名字只在该原型结束前可见。比如,下面的原型声明了3个名字(strDestination, numberOfElements 和 strSource);在原型结束处它们离开作用域。
errno_t strcpy_s( char *strDestination, size_t numberOfElements, const char *strSource );
enumeration scope
enum class altitude { high=’h’, low=’l’ }; void h() { altitude a; // OK a = high; // error: high not in scope a = altitude::low; // OK }
linkage
对象和函数名字在编译单元之间的共享方式被称为linkage。
external linkage | 标识符在其他编译单元可见 |
internal linkage | 标识符仅在本编译单元可见 |
no linkage | 标识符仅在它们的作用域内可见 |
internal linkage
- 显式声明为static的对象、引用、函数或函数模板。
- namespace scope(或file scope)中使用了说明符const,但没有显式使用extern或提前声明为external linkage的对象或引用。
- 匿名 union 中的数据成员。
- 匿名命名空间中声明的标识符。
external linkage
C
在C的 file scope中,没有使用static声明对象和函数的标识符具有external linkage。
static int a; extern int a;
则为 internal linkage。
C++
在 namespace scope 中,
- 不具有internal linkage的引用、对象、函数。
- 命名的类或enumeration,在typedef声明中定义的未命名的类或enumeration
- 具有external linkage的enumeration中的 enumerator
- 非internal linkage 的 模板
- 非匿名的namespace
如果一个类的标识符属于external linkage,那么它的 成员函数、静态数据成员、类scope中的类和enumeration也属于external linkage。
no linkage
- 函数参数
- block scope中未声明为 extern 或 static 的名字。
- Enumerators
- typedef语句中声明的名字。(例外,前面提到的未命名的类和enumeration)