一.基本常识
C++允许我们对名字的产生和名字的可见性进行控制,C语言可以通过使用static关键字使得名字只得在本编译单元内可见,在C++中我们可以通过一种命名空间来控制对名字的访问。
在C++中,名称(name)可以是常量符号、变量、宏、函数、结构体、枚举、类和对象等等
std是C++标准命名空间,C++标准程序库中的所有标识符都被定义在std中,比如标准库中的类iostream、vector等都定义在该命名空间中,使用时要加上using声明(using namespace std)或
using指示(如std::cout)
二、命名空间的使用
#include <iostream>
using namespace std;
int main() {
//1.不声明使用命名空间
std::cout<<"hello,world!"<<std::endl;
//2.使用using声明 using namespace std
cout<<"hello,world!"<<endl;
return 0;
}
1.命名空间的定义
namespace 名称
{
//定义变量、函数、类型...
}
2.命名空间成员的访问
使用作用域操作符 ::
空间名::成员
#include <iostream>
using namespace std;
//声明一个命名空间A
namespace A
{
int a;
void func()
{
cout<<"hello,A!"<<endl;
}
}
//声明一个命名空间B
namespace B
{
int a;
void func()
{
cout<<"hello,B!"<<endl;
}
}
int main() {
A::a = 100;
B::a = 10;
//1.空间中变量的访问
cout<<A::a<<endl;
cout<<B::a<<endl;
//2.空间中函数的访问
A::func();
B::func();
return 0;
}
3.命名空间只能全局范围内定义(以下错误写法)
void test() //函数里面定义命名空间 err
{
namespace A
{
int a;
}
namespace B
{
int b;
}
A::a=100;
B::b=200;
}
int main() {
test();
return 0;
}
error: 'namespace' definition is not allowed here namespace A
error: 'namespace' definition is not allowed here namespace B
4.命名空间嵌套定义
//命名空间的嵌套定义
namespace C
{
int a = 100;
namespace A
{
int b = 200;
}
}
int main() {
cout<<C::a<<endl;
cout<<C::A::b<<endl;
return 0;
}
5.将命名空间的声明和实现分开
将声明定义在.h里面,将实现定义在.cpp里面
6.命名空间别名
namespace studentInfo
{
void func()
{
cout<<"hello new student"<<endl;
}
}
int main() {
studentInfo::func();
//给命名空间取别名
namespace stdInfo = studentInfo;
stdInfo::func();
return 0;
}