Namespaces (스코프)

2024. 8. 2. 22:16프로그래밍 언어/C++

참고: https://en.cppreference.com/w/cpp/language/namespace

 

Namespaces - cppreference.com

Namespaces provide a method for preventing name conflicts in large projects. Entities declared inside a namespace block are placed in a namespace scope, which prevents them from being mistaken for identically-named entities in other scopes. Entities declar

en.cppreference.com

 

* 스코프 연산자 기준 위치

 - ns-name :: member-name

 

네임스페이스와 클래스 이름은 스코프 해석 연산자의 왼쪽에 위치해서 해당 네임스페이스나 클래스 내에 정의된 요소에 대한 접근할 수 있다.

 

예시 (ChatGPT 생성):

#include <iostream>

namespace Outer {
    int value = 5;
    
    namespace Inner {
        int value = 10;
        
        void display() {
            std::cout << "Inner value: " << value << std::endl;
        }
    }
    
    void display() {
        std::cout << "Outer value: " << value << std::endl;
    }
}

int main() {
    // 네임스페이스 외부에서 네임스페이스 요소에 접근
    std::cout << "Outer::value: " << Outer::value << std::endl;
    Outer::display();

    std::cout << "Inner::value: " << Outer::Inner::value << std::endl;
    Outer::Inner::display();

    return 0;
}
Outer::value: 5
Outer value: 5
Inner::value: 10
Inner value: 10