C++ 中可以嵌套命名空间吗?


是的,C++ 中可以嵌套命名空间。我们可以按照如下方式在另一个命名空间中定义一个命名空间 -

语法

namespace namespace_name1 {
   // code declarations
   namespace namespace_name2 {
      // code declarations
   }
}

你可以按照如下方式使用解析运算符来访问嵌套命名空间的成员 -

// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace:name1
using namespace namespace_name1;

示例

 在线演示

#include <iostream>
using namespace std;
// first name space
namespace first_space {
   void func() {
      cout << "Inside first_space" << endl;
   }
   // second name space
   namespace second_space {
      void func() {
         cout << "Inside second_space" << endl;
      }
   }
}
using namespace first_space::second_space;
int main () {
   // This calls function from second name space.
   func();
   return 0;
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Inside second_space

更新于: 2019-07-30

166 次浏览

开启你的 职业生涯

完成课程认证

立即开始
广告