namespace(命名空间)
关键词: namespaceA namespace declaration identifies and assigns a unique name to a user-declared namespace.
一个命名空间的声明标识符 和 赋值给一个用户使用命名空间的单一名字.
声明格式: namespace identifier
命名空间 标识符
定义实现的语法: namespace identifier
{
[ declaration-list ]
}
Such
namespaces are used to solve the problem of name collision in large
programs and libraries. Programmers can use namespaces to develop new
software components and libraries without causing naming conflicts with
existing components. [collision:难题 ;conflicts:冲突]
For example:
Copy Code
// namespace_declaration1.cpp
namespace X
{
int i;
double j;
}
int main()
{
X::i++;
}
命名空间的嵌套:
A
namespace-definition can be nested within another namespace-definition.
Every namespace-definition must appear either at file scope or
immediately within another namespace-definition.
For example:
Copy Code
// namespace_declaration2.cpp
// C2870 expected
namespace A
{
int j = 3;
int f(int k);
}
namespace Outer
{
int n = 6;
int func(int num);
namespace Inner
{
float f = 9.993;
}
}
int main()
{
namespace local // C2870: not at global scope
{
}
}
Unlike other declarative regions, the definition of a namespace can be split over several parts of a single translation unit.
For example:
// namespace_declaration3.cpp
namespace A
{
// declare namespace A variables
int i;
int j;
}
namespace B
{
}
namespace A
{
// declare namespace A functions
void func(void);
int int_func(int i);
}
int main()
{
}
When
a namespace is continued in this manner, after its initial definition,
the continuation is called an extension namespace definition. The
original definition of that namespace is known as an original namespace
definition.
Usage of this notation might be cumbersome with longer names or in large programs. The using declaration, using directive, and namespace aliases provide more straightforward ways to reference namespace members.
A namespace declaration, whether it involves a new namespace, an unnamed namespace, or an extended namespace definition, must be accompanied by a namespace body enclosed within curly braces. The statement
Copy Code
namespace X;
is a syntax error. The statement
Copy Code
namespace X{};
is not a syntax error, but is meaningless.
For background information, see Namespaces.
The identifier in an original namespace definition must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.
The declarative region of a namespace definition is its body. The body must be enclosed in curly braces ({}) and may contain declarations or definitions of variables, functions, objects, templates, and nested namespaces. The declarations in the declaration-list are said to be members of the namespace. The name of each namespace member is automatically qualified by the name of its namespace and the scope resolution operator.