using 命名空间
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <sstream>
using namespace std;
//命名空间
namespace A {//A是空间名
int a;
int f = 100;
void func();
namespace B {
int b = 40;
}
}
namespace N{
int c=30;
void func();
}
//注意6描述的,不加命名空间会导致链接错误 errlink 1120
void A::func() {
cout << "A::f" << endl;
}
//给命名空间取别名
void test01() {
namespace newA = A;
cout << newA::a << endl;
}
//类似 static int e=10;
namespace {
int e = 10;
}
/*命名空间的注意
注意1:命名空间只能卸载全局
注意2:命名空间可以嵌套命名空间
注意3:明明空间是开放的,可以在后期随时添加添加,新成员只能在加入后使用
注意4:可以有没有名字的命名空间
注意5;给命名空间取别名
注意6:分文件编写时候,如果.h中有两个命名空间,但是在里面成员函数或成员变量重名的同时,在.cpp实现函数时要加上对应的的命名空间
*/
int mya = 10;//全局常量区
int main()
{
int mya = 20;//栈区
cout << "mya=" << mya << endl;//打印的时候遵循就近远侧
cout << "::mya=" <<:: mya << endl;//::表示访问全局变量
cout <<"f="<<A::f<< endl;//表示访问明明空间内的变量 相当于是全局变量,不过被限制在namespace A中
cout << "b="<<A::B::b << endl;//访问嵌套空间,一层层访问
cout << "-------------" << endl;
A::func();
cout << "-------------" << endl;
cout <<"e="<< e << endl;
test01();
system("pause");
return 0;
}
using声明和编译指令
using namespace std;
namespace A
{
int a = 10;
int b = 20;
int c = 40;
}
//using声明 命名空间内某个变量可以直接使用
void test01() {
cout << A::a << endl;
using A::a;//改行后a可以直接使用,但在此之后不能定义同名变量a,因为这里相当于把a直接拿过来了
cout << a << endl;
}
//using编译指令 使得命名空间内的变量可以直接使用
void test02() {
using namespace A;//直接使用A内变量,但是这里可以定义同名变量a
//对比24行为啥不会报错
cout << a << endl;
cout << b << endl;
int a = 100;//这里int a为普通变量
}
int main()
{
test01();
test02();
system("pause");
return 0;
}