定义名字空间以 namespace 开头
右大括号后面不加分号
名字空间大括号内可以出现任何实体的声明或定义
使用名字空间中的内容
法一:名字空间名称::局部内容名
法二:提前声明 using namespace 名字空间名称;
声明之后可直接使用名字空间中所有内容
法三:using 名字空间名称::局部内容名
仅能使用该局部内容名注:不能写成 using namespace 名字空间名称:: 局部内容名
#include <iostream>
using namespace std;
namespace test_1
{
const int M = 200;
int inf = 10;
}
namespace test_2
{
int x;
int inf = -100;
}
using namespace test_1; //声明要加分号
using test_2::x;
int main()
{
x = -100;
cout << "inf=" << inf << endl;
//如果同时声明 using namespace test_2, inf 的使用会报错,因为此时存在2个 inf
cout << "M=" << M << endl;
cout << "test_2::inf=" << test_2::inf << endl;
test_2::inf *= 2;
cout << "test_2::inf=" << test_2::inf << endl;
cout << "x=" << x << endl;
return 0;
}