2.4.1 Namespace

C++가 지원하는 각종 요소들(변수, 함수, 클래스 등)을 한 범주로 묶어주기 위한 문법

소속이나 구역이라는 개념

 

#include "stdafx.h"
#include <iostream>

namespace TEST
{
	int g_nData = 100;
    
	void TestFunc(void)
	{
		std::cout << "TEST::TestFunc()" << std::endl;
	}
}
 
// _tmain은 Global namespace 소속
int _tmain(int argc, _TCHAR* argv[])
{
	TEST::TestFunc();
	// cout은 std 네임스페이스 소속
	std::cout << TEST::g_nData << std::endl;
    
	return 0;
}

 

2.4.2 Using

네임스페이스를 임의로 생략

#include "stdafx.h"
#include <iostream>

// declare std namespace with 'using' keyword
using namespace std;

namespace TEST
{
	int g_nData = 100;
    
	void TestFunc(void)
	{
		cout << "TEST::TestFunc()" << endl;
	}
}

// declare TEST namespace with 'using' keyword
using namespace TEST;

int _tmain(int argc, _TCHAR* argv[])
{
	TestFunc();
	cout << g_nData << endl;
    
	return 0;
}

 

2.4.3 nested Namespace

네임스페이스 안에 또 다른 네임스페이스가 속할 수 있음

#include "stdafx.h"
#include <iostream>

using namespace std;

namespace TEST
{
	int g_nData = 100;
    namespace DEV
    {
    	int g_nData = 200;
        namespace WIN
		{
        	int g_nData = 300;
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << TEST::g_nData << endl;
    cout << TEST::DEV::g_nData << endl;
    cout << TEST::DEV:WIN::g_nData << endl;
    
    return 0;
}

2.4.4 Namespace의 다중정의

#include "stdafx.h"
#include <iostream>

using namespace std;

//global
void TestFunc(void) { cout << "::TestFunc()" << endl;

namespace TEST
{
	void TestFunc(void){
    	cout << "TEST:TestFunc()" << endl;
	}
}

namespace MYDATA
{
	void TestFunc(void){
    	cout << "MYDATA::TestFunc()" << endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{

	TestFunc();	//implicitly global
    ::TestFunc();	//explicitly global
    TEST::TestFunc();
    MYDATA::TestFunc();
    
    return 0;
}

첫번째 TestFunc()은 별도의 Namespace를 지정하지 않았는데, _tmain()함수의 namespace가 전역이기 때문이다.

 

int TestFunc(int);
int Data::TestFunc(int);
int CMyData::TestFunc(int);
int CMyData::TestFunc(int) const;

1번은 소속이 없음, 2~3번은 속해 있는 namespace나 class가 존재함, 4번은 CMyData라는 클래스의 상수형 Method임

 

2.5.4 using 선언과 전역 변수

#include "stdafx.h"
#include <iostream>

using namespace std;

namespace TEST
{
	int nData = 200;
}

using namespace TEST;

int _tmain(int argc, _TCHAR* argv[])
{
	cout << nData << endl;
    
    return 0;
}

위의 예제에서 컴파일 에러가 발생함. nData가 전역 네임스페이스일 수도 TEST 네인스페이스일수도 있음

::nData라고 범위 식별자를 기술하거나, TEST::nData라고 정확하게 네임스페이스를 기술해야 함

반응형

'Prog&Algol' 카테고리의 다른 글

BJ | 2178 | BFS shorted path  (0) 2022.03.30
C++ | history of Class  (0) 2022.03.30
BJ | 9996 | connect server when missing Korea  (0) 2022.03.29
BJ | 2309 | 일곱 난쟁이 | Combination  (0) 2022.03.22
C++ | lower_bound & upper_bound  (0) 2022.03.22

+ Recent posts