c++ namespace的使用

时间:2022-09-07 09:42:16

** namespace:命名空间就是为解决C++中的变量、函数的命名冲突而服务的。

** namespace定义的格式基本格式是:

  namespace identifier
  {
      entities;
  }

  举个例子,
  namespace exp
  {
      int a,b;
  }

  为了在namespace外使用namespace内的变量,使用::操作符,如下

  exp::a
  exp::b

  使用namespace可以有效地避免重定义,

 #include <iostream>
using namespace std; namespace first
{
int var = ;
} namespace second
{
double var = 3.1416;
} int main () {
cout << first::var << endl;
cout << second::var << endl;
return ;
}

  结果是:
  5
  3.1416

  两个全局变量都是名字都是var,但是他们不在同一个namespace中所以没有冲突。

** using 关键字

  关键字using可以帮助从namespace中引入名字到当前的声明区域,

 #include <iostream>
using namespace std; namespace first
{
int x = ;
int y = ;
} namespace second
{
double x = 3.1416;
double y = 2.7183;
} int main () {
using first::x;
using second::y;
cout << x << endl;
cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
return ;
}
输出是 2.7183 3.1416
就如我们所指定的第一个x是first::x,y是second.y

  using也可以导入整个的namespace,

 #include <iostream>
using namespace std; namespace first
{
int x = ;
int y = ;
} namespace second
{
double x = 3.1416;
double y = 2.7183;
} int main () {
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return ;
}
输出是 3.1416
2.7183

** namespace也支持嵌套

 #include <iostream>

 namespace first
{
int a=;
int b=; namespace second
{
double a=1.02;
double b=5.002;
void hello();
} void second::hello()
{
std::cout <<"hello world"<<std::endl;
}
} int main()
{
using namespace first; std::cout<<second::a<<std::endl;
second::hello();
}
输出是
1.02
hello world

在namespace first中嵌套了namespace second,seond并不能直接使用,需要first来间接的使用。

** namespace 可以取别名

  在对一些名字比较长的namespace使用别名的话,是一件很惬意的事。但是与using相同,最好避免在头文件使用namespace的别名(f比first更容易产生冲突)。
namespace f = first;