对象、引用、函数、类型、模板和命名空间被统称为识别名称。每个识别名称都有三种连接类型:外部连接,内部连接和无连接。这些连接类型都规定了它在其他范围以及转译单元中的可见性。
识别名称的外部连接和程序的每个编译单元都有联系。比如:函数通常不被定义为静态的全局对象,常量对象可以定义为枚举类型等等。
下面列举了一些识别名称的外部连接方式:
int n; file://global non-static, hence external linkage
class C
{
void f(); // member functions
static int n;// static data members
};
extern const K; file://defined in a different translation unit
void func ();
namespace NS
{
class D{}; // qualified name NS::D has external linkage
}
enum DIR
{
Up,
Down
} // DIR, Up and Down have external linkage
识别名称的内部连接仅存在于编译单元的定义中。在一个命名空间中定义一个静态对象,那么这个命名空间的连接类型就是内部连接。匿名连接的成员、匿名命名空间的成员、typedef类型名,或者常量变量是不能定义成外部的。
下面举例说明识别名称的内部连接方式:
static void f(); file://a static function
static int q; file://a static object declared in global scope
namespace file://members of anonymous namespace
{
class C{};
int x;
}
const M=1000; file://const object not declared extern
union{ file://members of an anonymous union
int x;
float y;
};
typedefint I; // typedef names
无连接方式仅存在于识别名称被定义的范围。这些识别名称包括局部对象、局部类和局部类型。此外,不管识别名称是内部连接还是外部连接,它们都是无连接。
下面举例说明无连接方式:
int main()
{
class C{}; // C is a local class; has no linkage
int j; // local object not declared extern has no linkage
C c; // the object c has no linkage
{
file://types declared in this scope aren't visible elsewhere
enum Parity // local enum and enumerators
{
Even,
Odd
};
typedefint I; // local typedef
I i; file://OK
Parity x=Odd; file://OK
}
Parity x; file://error, Parity isn't recognized in this scope
I n; file://ditto
}
现在,我们可以利用不同的连接方式确定识别名称在不同范围和编译单元中的可见性了。