https://msdn.microsoft.com/en-us/library/5cb46ksf.aspx
http://www.cplusplus.com/doc/tutorial/namespaces/
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification. Identifiers outside the namespace can access the members by using the fully qualified name for each identifier, for example std::vector<std::string> vec;
, or else by a using Declaration for a single identifier (using std::string
), or a using Directive for all the identifiers in the namespace (using namespace std;
).Code in header files should always use the fully qualified namespace name.
The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members.
namespace ContosoData
{
class ObjectManager
{
public:
void DoSomething() {}
};
void Func(ObjectManager) {}
}
Use the fully qualified name:
ContosoData::ObjectManager mgr;
mgr.DoSomething();
ContosoData::Func(mgr);
Use a using declaration to bring one identifier into scope:
using WidgetsUnlimited::ObjectManager;
ObjectManager mgr;
mgr.DoSomething();
Use a using directive to bring everything in the namespace into scope:
using namespace WidgetsUnlimited;
ObjectManager mgr;
mgr.DoSomething();
Func(mgr);
Note |
---|
A using directive can be placed at the top of a .cpp file (at file scope), or inside a class or function definition. In general, avoid putting using directives in header files (*.h) because any file that includes that header will bring everything in the namespace into scope, which can cause name hiding and name collision problems that are very difficult to debug. Always use fully qualified names in a header file. If those names get too long, you can use a namespace alias to shorten them. |
You can declare that you are 'using' a namespace for a specific scope (such as a function). I should note (someone please correct me if I'm wrong) that in C++ you can arbitrarily declare a scope almost anywhere you want, simply by using curly braces.
{
using mynamespace;
/* rest of your code here */
}