###c++ 命名空间 namespace :
假设如果班级里有两个名字为 `小明` 的同学,为了区分他们 我们可能会在身高 长相 发型 等等其他条件判断谁是谁
编译器也是这样 当你写了 两个 函数名字一样的函数 编译器不知道引用哪一个
因此,引入了命名空间这个概念,专门用于解决上面的问题,它可作为附加信息来区分不同库中相同名称的函数、类、变量
等。使用了命名空间即定义了上下文。本质上,命名空间就是定义了一个范围
####定义命名空间:
namesoace xxx{
//code
}
用关键字 namespace
demo:
#include <iostream>
namespace first_space {
//相同的函数名字 不同的命名空间
void fun_() {
std::cout << "this is first_space" << std::endl;
}
}
namespace second_space {
void fun_() {
std::cout << "this is second_space" << std::endl;
}
}
int main()
{
//命名空间1
first_space::fun_();
//命名空间2
second_space::fun_();
system("pause");
return 0;
}
using 指令
您可以使用 using namespace 指令,这样在使用命名空间时就可以不用在前面加上命名空间的名称。
这个指令会告诉编译器,后续的代码将使用指定的命名空间中的名称
#include <iostream>
namespace first_space {
void fun_() {
std::cout << "this is first_space" << std::endl;
}
}
namespace second_space {
void fun_() {
std::cout << "this is second_space" << std::endl;
}
}
using namespace first_space; //使用命名空间1
int main()
{
fun_();
system("pause");
return 0;
}
using 指令也可以用来指定命名空间中的特定项目。例如,如果您只打算使用 std 命名空间中的 cout 部分.
using std::cout;
using std::cout;//指定命名空间中的特定项目
int main()
{
//cout 可以不加 命名空间,endl 还是需要加
cout << "Hello namespace!" << std::endl;
system("pause");
return 0;
}
###嵌套的命名空间:
namespace xxx{
//code
namespace xxx{
//code
}
}
demo:
#include <iostream>
//嵌套的命名空间
namespace first_space {
void fun_() {
std::cout << "this is first_space" << std::endl;
}
namespace second_space {
void fun_() {
std::cout << "this is second_space" << std::endl;
}
}
}
int main()
{
//命名空间1
first_space::fun_();
//命名空间2
first_space::second_space::fun_();
system("pause");
return 0;
}
也可以用 using
指令 using namespace first_space::second_space;
using namespace first_space::second_space;
int main()
{
fun_();
system("pause");
return 0;
}
98年菜鸟一枚,请大佬们多多关照!