一、namespace命名空间
- 命名空间用途:解决名称冲突
- 命名空间下可以存放 : 变量、函数、结构体、类…
- 命名空间必须要声明在全局作用域
- 命名空间可以嵌套命名空
- 命名空间是开放的,可以随时将新成员添加到命名空间下
- 命名空间可以匿名的
- 命名空间可以起别名
使用示例
main.c
#include <iostream>
#include"start1.h"
#include"start2.h"
#include"start3.h"
using namespace std;
namespace A {
int A_a=10;
int A_b=20;
}
void ns() {
using namespace s1;
using namespace A;
test();
cout << A_a << endl;
}
int main()
{
bool tag = true;
namespace ABC = A;
s1::test();
s2::test();
s3::s4::test();
cout << "Hello World!"<<endl;
cout << ABC::A_a << endl;
cout<< A::A_b << endl;
ns();
system("pause");
return EXIT_SUCCESS;
}
start3.h、start3.cpp
//start3.h
#pragma once
#include<iostream>
using namespace std;
namespace s3 {
namespace s4 {
void test();
}
}
//start3.cpp
#include"start3.h"
void s3::s4::test() {
cout<<"start 3" << endl;
}
start2.h、start2.cpp
//start2.cpp
#pragma once
#include<iostream>
using namespace std;
namespace s2
{
void test();
}
//start2.h
#include"start2.h"
void s2::test() {
cout<<"start 2" << endl;
}
start1.h、start1.cpp
//start.h
#pragma once
#include<iostream>
using namespace std;
namespace s1
{
void test();
}
//start1.cpp
#include"start1.h"
void s1::test() {
cout << "start 1"<<endl;
}