Usage :
To create a separate region for a group of variables, functions and classes etcCreating Namespace :
namespace{
Members of namespace ;
}
Usage Namespace_name::member_variable_name.
namespace myconstants {
const double pi = 3.141592;
}
usage =>
myconstants::pi
Namespaces have the following important points:1) We can have more than one namespace of the same name. This gives the advantage of defining the same namespace in more than one file (although they can be created in the same file as well).
2)We can have anonymous namespaces (namespace with no name). They are directly usable in the same program and are used for declaring unique identifiers. It also avoids making global static variable.
The “anonymous” namespace you have created will only be accessible within the file you created it in.
3) C++ has a default namespace named std, which contains all the default library of the C++ included using #include directive.
Using Namespaces
Namespaces are used with the ‘using’ keyword, which makes all the members of the namespace available in the current program and the members can be used directly, without taking reference of the namespace.Namespaces are also usable by taking their name reference with scope resolution operator. This method allows distinguishing between the members of the same name in two different namespaces.
ex:
using namespace std; and use cout directly
else
use std::cout .
Namespace alias
It is also possible to declare an alternate name for an existing namespace. namespace new_name = current_name;
No comments:
Post a Comment