命名空间的语法:
namespace xy //xy为空间名
{
int a;
int b;
int c;
};
命名空间的使用:
静态变量 :
匿名空间
namespace
{
int a;
}
作用与静态变量static相似,外部无法访问空间内的数据
命名空间的跨文件的使用
文件1:
#include <iostream>
using namespace std;
//声明为外部变量
extern int all;
namespace TS
{
extern int b; //声明空间中的数据为外部定义
}
void show_static()
{
// cout << all << endl;
// cout << a << endl;
cout << "TS::b" << TS::b << endl;
}
文件2:
#include <iostream>
using namespace std;
//定义一个 静态 全局变量
//static int all=100; //添加 static 限制在本文件中使用
int all=100;
//显示静态变量中的数据
void show_static();
namespace{
//定义一个匿名空间
int a=10086;
}
namespace TS
{
int b=10010;
}
int main()
{
//访问全局变量
show_static();
//在本文件中访问匿名空间
cout << a << endl;
cout << TS::b << endl;
}