💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
#### 30. 命名空间 **定义命名空间:** 命名空间的定义使用关键字 **namespace**,后跟命名空间的名称,如下所示: ~~~ namespace namespace_name { // 代码声明 } 复制代码 ~~~ 为了调用带有命名空间的函数或变量,需要在前面加上命名空间的名称,如下所示: ~~~ name::code; // code 可以是变量或函数 复制代码 ~~~ 让我们来看看命名空间如何为变量或函数等实体定义范围: ~~~ //1. 定义命名空间 namespace test1_space { void func() { cout << "test1_space" << endl; } } namespace test2_space { void func2() { cout << "test2_space" << endl; } } void test27() { test1_space::func(); test2_space::func2(); } 复制代码 ~~~ > **输出:** > > test1\_space test2\_space **using 指令:** 您可以使用 **using namespace** 指令,这样在使用命名空间时就可以不用在前面加上命名空间的名称。这个指令会告诉编译器,后续的代码将使用指定的命名空间中的名称。 ~~~ //1. 定义命名空间 namespace test1_space { void func() { cout << "test1_space" << endl; } } namespace test2_space { void func2() { cout << "test2_space" << endl; } } //2. 使用 using 指令 using namespace test1_space; using namespace test2_space; void test27() { //1. test1_space::func(); test2_space::func2(); //2. func(); func2(); } 复制代码 ~~~ > **输出:** > > test1\_space test2\_space > > test1\_space test2\_space