namesapce命名空间
namesapce命名空间是在大型项目开发中,为了避免命名冲突而引入的一种机制,比如说,在一个大型项目中,要用到多家软件开发商提供的类库。在事先没有约定的情况下,两套类库可能存在同名的函数或者是全局变量而产生冲突。项目越大,用到的类库越多,开发人员越多,这样的冲突也就越明显。
所以在C++中,为了避免这种问题的发生,引入了命名空间,namespace 是对全局区域的再次划分。
1. 命名空间的申明
namespace NAMESPACE
{
全局变量 int a;
数据类型 struct Stu{};
函数 void fun();
其他命名空间 namespace
}
2. 使用方法
a. 直接指定命名空间
Space:: a = 5;
b. 使用using+命名空间+空间元素
using Space::a;
a = 2000;
c. 使用using + namespace +命名空间
我们经常用到的 using namespace std;
3. 下面我们看看以下几个例子。
#include <iostream>
using namespace std;
namespace MySpace
{
int val = 5;
int x,y,z;
}
void main()
{
MySpace::x = 1;
MySpace::y = 2;
MySpace::z = 3;
cout << MySpace::x << "," << MySpace::y << "," << MySpace::z << endl;
system("Pause");
}
这样子写是不是很麻烦,每次都要加上命名空间名。所以我们经常采用c这种方式。
#include <iostream>
using namespace std;
namespace MySpace
{
int val = 5;
int x,y,z;
}
void main()
{
using namespace MySpace;
x = 1;
y = 2;
z = 3;
cout << x << "," << y << "," << z << endl;
system("Pause");
}
使用namespace可以有效的避免重定义的问题。
#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;
}
两个全局变量都是名字都是var,但是他们不在同一个namespace中所以没有冲突。
命名空间也支持嵌套,看下面的例子。
#include <iostream>
using namespace std;
namespace MySpace
{
int x = 1;
int y = 2;
namespace Other {
int m = 3;
int n = 4;
}
}
int main()
{
using namespace MySpace::Other;
cout << m << "," << n <<endl;
system("Pause");
return 0;
}
4. 协作方法
同名命名空间自动合并,对于一个命名空间中的类,要包含声明和实现。
a.h
#ifndef A_H
#define A_H
namespace XX {
class A
{
public:
A();
~A();
};
}
#endif // A_H
a.cpp
<span style="font-size:18px;">#include "a.h"
using namespace XXX
{
A::A()
{}
A::~A()
{}
}</span>
b.h
<span style="font-size:18px;">#ifndef B_H
#define B_H
namespace XX
{
class B
{
public:
B();
~B();
};
}
#endif // B_H</span>
b.cpp
#include "b.h"
namespace XX {
B::B()
{}
B::~B()
{}
}
main.cpp
#include <iostream>
#include "a.h"
#include "b.h"
using namespace std;
using namespace XX;
int main()
{
A a;
B b;
return 0;
}
以上内容参考王桂林老师的教学视频。以上代码在VS2013上面验证通过。