Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

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;
}

출력

Inside second_space