Namespaces (기본 네임스페이스)

2024. 7. 29. 22:59프로그래밍 언어/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

 

 

네임스페이스는 C++에서 식별자(변수, 함수, 클래스 등)의 이름 충돌을 방지하기 위해 사용되는 기능으로 네임스페이스를 사용하면 동일한 이름을 가진 식별자들을 구분해서 사용할 수 있다. 코드의 가독성이 높아지고 유지보수가 용이해지는 C와는 다른 C++의 특징.

 

* 기본적인 네임스페이스 선언

- namespace ns-name { declarations }

 

예시 (ChatGPT 생성):

#include <iostream>

namespace MyNamespace {
    int value = 42;
    
    void printValue() {
        std::cout << "MyNamespace value: " << value << std::endl;
    }
}

namespace AnotherNamespace {
    int value = 100;
    
    void printValue() {
        std::cout << "AnotherNamespace value: " << value << std::endl;
    }
}

int main() {
    // 네임스페이스를 사용하여 함수 호출
    MyNamespace::printValue();      // 출력: MyNamespace value: 42
    AnotherNamespace::printValue(); // 출력: AnotherNamespace value: 100
    
    // 네임스페이스를 사용하지 않으면 이름 충돌 발생
    // int value = 200; // 전역 범위에서 'value' 변수 선언
    
    // std::cout << value << std::endl; // 주석 해제시, 'value'가 정의되지 않아 오류 발생
    
    return 0;
}

'프로그래밍 언어 > C++' 카테고리의 다른 글

Namespaces (using - namespace의 특정 맴버)  (0) 2024.08.03
Namespaces (using)  (0) 2024.08.03
Namespaces (스코프)  (0) 2024.08.02
Namespaces (익명 네임스페이스)  (0) 2024.07.30
Namespaces (인라인 네임스페이스)  (0) 2024.07.29