在STL程序中一般需要有一行"using namespace std;",这就是命名空间的应用。为了避免和其他头文件冲突, STL的头文件不再使用常规的.h扩展。而是要使用命名空间namespace.在C++中,名称可以是变量、函数、结构、枚举以及类和结构的成员。随着工程的增大,这些名称相互冲突的可能就增加。当使用多个厂商的类库时,也可能导致名称冲突。C++中的namespace命名空间的提出就可以很好的解决该问题,这也实现了再封装。
namespace使用实例:
1 #include<stdio.h>
2
3 namespace mycompany
4 {
5 void func()
6 {
7 printf("Hello,this is my company\n");
8 }
9 };
10 namespace yourcompany
11 {
12 void func()
13 {
14 printf("Hello,this is your company\n");
15 }
16 };
17 using namespace mycompany;
18 int main(int argc,char* argv[])
19 {
20 func();
21 yourcompany::func();
22 return 0;
23 }
2
3 namespace mycompany
4 {
5 void func()
6 {
7 printf("Hello,this is my company\n");
8 }
9 };
10 namespace yourcompany
11 {
12 void func()
13 {
14 printf("Hello,this is your company\n");
15 }
16 };
17 using namespace mycompany;
18 int main(int argc,char* argv[])
19 {
20 func();
21 yourcompany::func();
22 return 0;
23 }
运行结果:Hello,this is my company
Hello,this is your company
由于STL的命名空间名称为std,所以在应用STL时候,必须得包含using namespace std;