第 14 節

命名空间

0瀏覽次數0訪問次數--跳出率--平均停留

Namespace and Name Conflicts

In a C++ application. For example, you might write a function named xyz(), and another available library also contains an identical function xyz(). In this case, the compiler cannot determine which xyz() function you are using.

Therefore, the concept of namespace was introduced specifically to solve the above problem. It serves as additional information to distinguish functions, classes, variables, etc. that share the same name across different libraries. Using a namespace defines a context. Essentially, a namespace defines a scope.

Define the namespace

The definition of a namespace uses the keyword namespace, followed by the name of the namespace, as shown below:

namespace namespace_name {
   // 代码声明
}

运行结果: 此代码块不含 main 函数,是语法、接口或分文件示例,不能独立运行,因此没有终端输出。

To call a function or variable with a namespace, you need to prefix it with the namespace name, as shown below:

name::code;  // code 可以是变量或函数

运行结果: 此代码块不含 main 函数,是语法、接口或分文件示例,不能独立运行,因此没有终端输出。

using the command

You can use the using namespace directive, so that when using the namespace, you don't need to prefix it with the namespace name. This directive tells the compiler that subsequent code will use names from the specified namespace.

#include <iostream>
using namespace std;

// 第一个命名空间
namespace first_space{
   void func(){
      cout << "Inside first_space" << endl;
   }
}
// 第二个命名空间
namespace second_space{
   void func(){
      cout << "Inside second_space" << endl;
   }
}

// 第三个命名空间
namespace third_space{
   void func()
   {
      cout << "Inside second_space" << endl;
   }
}

using namespace first_space;
using second_space::func;    //(与25行代码建议不能共存,因为都导入了func()函数),(这种方法更好更推荐)

int main ()
{

   // 调用第一个命名空间中的函数
   func();
   // 调用第二个命名空间中的函数   
   func();         //(与32行代码不能共存)
   //调用第三个命名空间中的函数
   third_space::func();

   return 0;
}

运行结果: 编译失败:using namespace 把两个同名 func() 同时引入当前作用域,调用 func() 时产生二义性。

Nested namespaces

Namespaces can be nested. You can define one namespace inside another, as shown below:

namespace namespace_name1 {
   // 代码声明
   namespace namespace_name2 {
      // 代码声明
   }
}

运行结果: 此代码块不含 main 函数,是语法、接口或分文件示例,不能独立运行,因此没有终端输出。

You can access members in a nested namespace by using the :: operator:

// 访问 namespace_name2 中的成员
using namespace namespace_name1::namespace_name2;

// 访问 namespace_name1 中的成员
using namespace namespace_name1;

运行结果: 此代码块不含 main 函数,是语法、接口或分文件示例,不能独立运行,因此没有终端输出。

音乐页