We should know that the traditional C + + has only one global namespace, but because of the growing size of the current program, the division of the program is becoming more and more thin, global scope becomes more and more crowded, everyone may use the same name to implement different libraries, As a result, programmers may have conflicting names when merging programs. namespace introduces complexity and solves the problem. namespace allows like classes, objects, and functions to be clustered under a name. Essentially, namespace is a subdivision of the global scope. I think we've all seen a procedure like this:
hello_world.c
#include <iostream>
using namespace std;
int main()
{
printf("hello world !");
return 0;
}
I think a lot of people know so much about namespace, but namespace is far more than that, let's learn more about namespace
The basic format of the namespace format isnamespace identifier
{
entities;
}
举个例子,
namespace exp
{
int a,b;
}
It's kind of like a class, but it's completely two different types.
In order to use the variables in namespace outside the namespace we use:: operator, as follows
Exp::a
Exp::b
Using namespace can be an effective way to avoid redefining problems
#include <iostream>
using namespace std;
namespace first
{
int var = 5;
}
namespace second
{
double var = 3.1416;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
The result is
5
3.1416