共用方式為


namespace Declaration

A namespace declaration identifies and assigns a unique name to a user-declared namespace.

namespace identifier

Remarks

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.

For example:

// namespace_declaration1.cpp
namespace X
{
   int i;
   double j;
}
int main()
{
   X::i++;
}

The syntax for a namespace definition is:

namespace identifier
{
   [ declaration-list ]
}

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:

// 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.

// 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

namespace X;

is a syntax error. The statement

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.

See Also

Reference

Namespaces (C++)

C++ Keywords

Unnamed Namespaces