- 네임스페이스는 식별자, 즉 변수, 메소드, 클래스를 정의하거나 선언할 수 있는 공간을 제공합니다.
- 네임스페이스를 사용하면 변수, 메서드, 클래스 등 식별자가 정의되는 공간이나 컨텍스트를 정의할 수 있습니다. 본질적으로 네임스페이스는 범위를 정의합니다.
이름 충돌을 피하기 위한 네임스페이스의 이점
- 예를 들어, xyz()라는 함수가 있는 일부 코드를 작성 중이고 동일한 함수 xyz()가 있는 다른 라이브러리가 있을 수 있습니다. 이제 컴파일러는 코드 내에서 참조하고 있는 xyz() 함수의 버전을 알 수 없습니다.
- 네임스페이스는 이러한 어려움을 극복하기 위해 설계되었으며 서로 다른 라이브러리에서 사용 가능한 동일한 이름을 가진 유사한 함수, 클래스, 변수 등을 구별하기 위한 추가 정보로 사용됩니다.
- 네임스페이스 범위의 가장 좋은 예는 모든 클래스, 메서드 및 템플릿이 선언되는 C++ 표준 라이브러리(std)입니다. 따라서 C++ 프로그램을 작성하는 동안 우리는 일반적으로 네임스페이스 std를 사용하여 지시문을 포함합니다.
네임스페이스 정의:
- 네임스페이스 정의는 다음과 같이 네임스페이스 키워드로 시작하고 그 뒤에 네임스페이스 이름이 옵니다.
namespace namespace_name { // code declarations i.e. variable (int a;) method (void add();) classes ( class student{};) }> - 닫는 중괄호 뒤에는 세미콜론(;)이 없다는 점에 유의하세요.
- 함수 또는 변수의 네임스페이스 지원 버전을 호출하려면 다음과 같이 네임스페이스 이름을 앞에 추가하세요.
- 네임스페이스_이름: :code; // 코드는 변수, 함수 또는 클래스일 수 있습니다.
사용 지시문:
- using 네임스페이스 지시문을 사용하면 네임스페이스가 앞에 추가되는 것을 방지할 수도 있습니다. 이 지시문은 후속 코드가 지정된 네임스페이스의 이름을 사용하고 있음을 컴파일러에 알립니다.
- 따라서 네임스페이스는 다음 코드에 대해 암시됩니다.
C++
#include> 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;> int> main ()> {> >// This calls function from first name space.> >func();> >return> 0;> }> |
>
>산출
Inside first_space>
- using 지시문에 도입된 이름은 일반 범위 규칙을 따릅니다. 이름은 using 지시문 지점부터 지시문이 있는 범위 끝까지 표시됩니다. 외부 범위에 정의된 동일한 이름을 가진 엔터티는 숨겨집니다.
중첩된 네임스페이스:
- 네임스페이스는 다음과 같이 다른 네임스페이스 내에 하나의 네임스페이스를 정의할 수 있는 중첩될 수 있습니다.
SYNTAX: namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } }> 다음과 같이 확인 연산자를 사용하여 중첩된 네임스페이스의 멤버에 액세스할 수 있습니다.
//namespace_name2의 멤버에 액세스합니다.
네임스페이스 네임스페이스_name1::namespace_name2 사용;
//namespace_name1의 멤버에 액세스합니다.
네임스페이스 네임스페이스_name1 사용;
위 문에서 네임스페이스_이름1을 사용하는 경우 다음과 같이 범위에서 네임스페이스_이름2의 요소를 사용할 수 있게 됩니다.
C++
#include> 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>
변수와 함수를 포함한 엔터티의 네임스페이스 범위를 어떻게 지정하는지 살펴보겠습니다.
C++
#include> 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;> >}> }> int> main ()> {> >// Calls function from first name space.> >first_space :: func();> >// Calls function from second name space.> >second_space :: func();> >return> 0;> }> |
>
자바 안녕하세요 세계
>산출
Inside first_space Inside second_space>
다음 C++ 프로그램을 고려해보세요.
CPP
라텍스 테이블
// A program to demonstrate need of namespace> int> main()> {> >int> value;> >value = 0;> >double> value;>// Error here> >value = 0.0;> }> |
>
>
출력 :
Compiler Error: 'value' has a previous declaration as 'int value'>
각 범위에서 이름은 하나의 엔터티만 나타낼 수 있습니다. 따라서 동일한 범위에 동일한 이름을 가진 두 개의 변수가 있을 수 없습니다. 네임스페이스를 사용하면 동일한 이름을 가진 두 개의 변수나 멤버 함수를 만들 수 있습니다.
CPP
// Here we can see that more than one variables> // are being used without reporting any error.> // That is because they are declared in the> // different namespaces and scopes.> #include> using> namespace> std;> // Variable created inside namespace> namespace> first {> int> val = 500;> }> // Global variable> int> val = 100;> int> main()> {> >// Local variable> >int> val = 200;> >// These variables can be accessed from> >// outside the namespace using the scope> >// operator ::> >cout << first::val <<>'
'>;> >return> 0;> }> |
>
>산출
500>
정의 및 생성: 네임스페이스를 사용하면 명명된 엔터티를 그룹화할 수 있습니다. 글로벌 범위 더 좁은 범위로 나누어서 네임스페이스 범위 . 이를 통해 프로그램 요소를 이름으로 참조되는 다양한 논리적 범위로 구성할 수 있습니다. 네임스페이스는 식별자, 즉 변수 이름, 메소드, 클래스 등을 정의하거나 선언할 수 있는 공간을 제공합니다.
- 네임스페이스는 C++에 추가된 기능이며 C에는 없습니다.
- 네임스페이스는 내부의 식별자(함수 이름, 변수 또는 기타 사용자 정의 데이터 유형)에 범위를 제공하는 선언적 영역입니다.
- 동일한 이름을 가진 여러 네임스페이스 블록이 허용됩니다. 해당 블록 내의 모든 선언은 명명된 범위에서 선언됩니다.
네임스페이스 정의는 키워드로 시작됩니다. 네임스페이스 그 뒤에는 다음과 같이 네임스페이스 이름이 옵니다.
namespace namespace_name { int x, y; // code declarations where // x and y are declared in // namespace_name's scope }> - 네임스페이스 선언은 전역 범위에서만 나타납니다.
- 네임스페이스 선언은 다른 네임스페이스 내에 중첩될 수 있습니다.
- 네임스페이스 선언에는 액세스 지정자(Public 또는 Private)가 없습니다.
- 네임스페이스 정의의 닫는 중괄호 뒤에 세미콜론을 제공할 필요가 없습니다.
- 네임스페이스 정의를 여러 단위로 나눌 수 있습니다.
네임스페이스 정의:
네임스페이스 정의는 다음과 같이 네임스페이스 키워드로 시작하고 그 뒤에 네임스페이스 이름이 옵니다.
C++
namespace> namespace_name{> >// code declarations i.e. variable (int a;)> >method (>void> add();)> >classes (>class> student{};)> }> |
>
>
닫는 중괄호 뒤에는 세미콜론(;)이 없다는 점에 유의하세요.
함수나 변수의 네임스페이스 지원 버전을 호출하려면 다음과 같이 네임스페이스 이름을 앞에 추가하세요.
네임스페이스_이름: :code; // 코드는 변수, 함수 또는 클래스일 수 있습니다.
C++
// Let us see how namespace scope the entities including variable and functions:> #include> 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;> >}> }> int> main ()> {> >// Calls function from first name space.> >first_space::func();> >// Calls function from second name space.> >second_space::func();> >return> 0;> }> // If we compile and run above code, this would produce the following result:> // Inside first_space> // Inside second_space> |
>
>산출
Inside first_space Inside second_space>
사용 지시문:
using 네임스페이스 지시문을 사용하면 네임스페이스가 앞에 추가되는 것을 방지할 수 있습니다. 이 지시문은 후속 코드가 지정된 네임스페이스의 이름을 사용하고 있음을 컴파일러에 알립니다. 따라서 네임스페이스는 다음 코드에 대해 암시됩니다.
C++
#include> 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;> int> main ()> {> >// This calls function from first name space.> >func();> >return> 0;> }> // If we compile and run above code, this would produce the following result:> // Inside first_space> |
>
>산출
Inside first_space>
전체 네임스페이스에 액세스하는 대신 다른 옵션( 사용하여 선언)은 네임스페이스 내의 특정 항목에 액세스하는 것입니다. 예를 들어, 사용하려는 std 네임스페이스의 유일한 부분이 cout인 경우 다음과 같이 참조할 수 있습니다.
std::cout 사용;
후속 코드는 네임스페이스 앞에 추가하지 않고 cout을 참조할 수 있지만 std 네임스페이스의 다른 항목은 여전히 다음과 같이 명시적이어야 합니다.
C++
#include> using> std::cout;> int> main ()> {> >cout <<>'std::endl is used with std!'> << std::endl;> >return> 0;> }> |
>
>산출
std::endl is used with std!>
using 지시문에 도입된 이름은 일반적인 범위 규칙을 따릅니다. 즉, using 지시문이 발생하는 지점부터 지시문이 발견되는 범위의 끝까지 표시됩니다. 외부 범위에 정의된 동일한 이름을 가진 엔터티는 숨겨집니다.
C++
닉 풀로스 블랙 라이트닝
// Creating namespaces> #include> using> namespace> std;> namespace> ns1 {> int> value() {>return> 5; }> }>// namespace ns1> namespace> ns2 {> const> double> x = 100;> double> value() {>return> 2 * x; }> }>// namespace ns2> int> main()> {> >// Access value function within ns1> >cout << ns1::value() <<>'
'>;> >// Access value function within ns2> >cout << ns2::value() <<>'
'>;> >// Access variable x directly> >cout << ns2::x <<>'
'>;> >return> 0;> }> |
>
>
산출:
5 200 100>
클래스 및 네임스페이스: 다음은 네임스페이스에 클래스를 만드는 간단한 방법입니다.
C++
// A C++ program to demonstrate use of class> // in a namespace> #include> using> namespace> std;> namespace> ns> {> >// A Class in a namespace> >class> geek> >{> >public>:> >void> display()> >{> >cout<<>'ns::geek::display()'>< } }; } int main() { // Creating Object of geek Class ns::geek obj; obj.display(); return 0; }> |
>
>산출
ns::geek::display()>
클래스는 네임스페이스 내부에서 선언되고 네임스페이스 외부에서 정의될 수도 있습니다. 다음 구문을 사용합니다.
CPP
// A C++ program to demonstrate use of class> // in a namespace> #include> using> namespace> std;> namespace> ns {> // Only declaring class here> class> geek;> }>// namespace ns> // Defining class outside> class> ns::geek {> public>:> >void> display() { cout <<>'ns::geek::display()
'>; }> };> int> main()> {> >// Creating Object of geek Class> >ns::geek obj;> >obj.display();> >return> 0;> }> |
>
>
자바 문자열 조인산출
ns::geek::display()>
네임스페이스 외부에서도 메서드를 정의할 수 있습니다. . 다음은 예제 코드입니다.
C++
// A C++ code to demonstrate that we can define> // methods outside namespace.> #include> using> namespace> std;> // Creating a namespace> namespace> ns {> void> display();> class> geek {> public>:> >void> display();> };> }>// namespace ns> // Defining methods of namespace> void> ns::geek::display()> {> >cout <<>'ns::geek::display()
'>;> }> void> ns::display() { cout <<>'ns::display()
'>; }> // Driver code> int> main()> {> >ns::geek obj;> >ns::display();> >obj.display();> >return> 0;> }> |
>
>
산출:
ns::display() ns::geek::display():>
중첩된 네임스페이스:
네임스페이스는 중첩될 수 있습니다. 즉, 다음과 같이 다른 네임스페이스 내에 하나의 네임스페이스를 정의할 수 있습니다.
C++
namespace> namespace_name1 {> >// code declarations> >namespace> namespace_name2 {> >// code declarations> >}> }> |
>
>
다음과 같이 확인 연산자(::)를 사용하여 중첩된 네임스페이스의 멤버에 액세스할 수 있습니다.
C++
여러 줄 주석 파워쉘
// to access members of namespace_name2> using> namespace> namespace_name1::namespace_name2;> // to access members of namespace:name1> using> namespace> namespace_name1;> |
>
>
위 문에서 네임스페이스_이름1을 사용하는 경우 다음과 같이 범위에서 네임스페이스_이름2의 요소를 사용할 수 있게 됩니다.
C++
#include> 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;> }> // If we compile and run above code, this would produce the following result:> // Inside second_space> |
>
>산출
Inside second_space>
네임스페이스는 이름 충돌을 방지하는 이점을 제공합니다.
예를 들어, xyz()라는 함수가 있는 일부 코드를 작성 중일 수 있으며 코드에 동일한 xyz() 함수가 있는 다른 라이브러리가 있을 수 있습니다. 이제 컴파일러는 코드 내에서 참조하고 있는 xyz() 함수의 버전을 알 수 없습니다.
네임스페이스는 이러한 어려움을 극복하기 위해 고안되었으며, 서로 다른 라이브러리에서 사용 가능한 동일한 이름을 가진 유사한 함수, 클래스, 변수 등을 구별하기 위한 추가 정보로 사용됩니다.
네임스페이스 범위의 가장 좋은 예는 모든 클래스, 메서드 및 템플릿이 선언되는 C++ 표준 라이브러리(std)입니다. 따라서 C++ 프로그램을 작성하는 동안 일반적으로 다음 지시문을 포함합니다.
네임스페이스 std 사용;
C++의 네임스페이스 | 세트 2(확장 네임스페이스 및 이름 없는 네임스페이스) C++의 네임스페이스 | 세트 3(액세스, 헤더 생성, 중첩 및 별칭 지정) C++에서 네임스페이스를 중첩할 수 있습니까? 참조 : http://www.cplusplus.com/doc/tutorial/namespaces/