命名空间的使用
#include<iostream>
#include<cstdlib>
using namespace std;
namespace string1
{
char str[10]{ "calc" };
void show()
{
//cout << "holle" << endl;
cout << str << endl;
}
}
namespace string2
{
char str[10]{ "notepad" };
}
void main()
{
//命名空间的函数与变量
system(string1::str);//calc
system(string2::str);//notepad
string1::show();//holle
cin.get();
}
命名空间的权限
#include<iostream>
using namespace std;
namespace data
{
//private int num;//报错,命名空间不存在私有的概念
int num;
void show()
{
cout << num << endl;
}
}
using namespace data;//使用命名空间
namespace dataX
{
int num = 100;
namespace run
{
int num = 10;
void show()//命名空间里内层覆盖外层
{
//cout << ::num << endl;//直接访问全局变量,全局变量不存在就返回0
cout << num << endl;
cout << dataX::num << endl;//100
}
}
}
using namespace dataX;//使用命名空间必须在定义之后
void main1()
{
//num = 10;//报错,num不明确,需要指明一下
data::num = 10;//指明是data里的num
show();
cin.get();
}
void main()
{
dataX::run::show();//10
cin.get();
}
命名空间的意义
main.h
//int num = 20;//多重定义 外部全局变量冲突
//data命名空间的名称
namespace data
{
int num = 20;//解决外部全局变量冲突
}
namespace.cpp
#include<iostream>
#include"main.h"
using namespace std;
int num = 10;
void main()
{
cout << num << endl;//10
cout << data::num << endl;//20
cin.get();
}
std和别名
#include<iostream>
//using,可以省略std std标准空间
//制定命名空间
//原则禁止using namespace std;//明确空间
//可以给自己定义的起别名,不推荐跟标准起别名
namespace bobo = std;//可以替换 别名的作用 自己创建的空间也可以
void main()
{
std::cout << "holle";
std::cin.get();
bobo::cout << "holle";
bobo::cin.get();
}
匿名命名空间
#include<iostream>
#include<cstdlib>
using namespace std;
//匿名命名空间相当于全局变量
namespace
{
int x = 10;
}
//int x = 5;//报错
void main()
{
cout << x << endl;//10
cin.get();
}