using 지시자와 using 선언의 차이점에대해서 알려주세요!
조회수 2040회
c++ 공부를 시작했는데 namespace 공부를 하다가 막혔습니다. ㅠㅠ 궁금한 점에 대해서 구글링 하던중, 답은 못찾았고 저랑 정확하게 같은 궁금증을 가진 분이 올린 질문을 찾았습니다. 다음은 그 질문을 편집한 것입니다.
Say for example there are 100 name definitions in the namespace std, if I were to include all of them using the "using" declaration (Option1), it still would not be the same as "using" directive (Option2)
Option1 - using declaration Code: using std::cout; using std::cin; .... //Assume I mention all the rest of the name definition in std using std::
Option2 - using directive Code: using namespace std; Now option1 and option2 (assuming they are specified in the same point in the code) aren't the same, I would like to know how / why they are different.
assuming there are 2 namesaces "Hello" and "GoodBye" and both have a function message().
Test1 - Following is legal: Code:
using namespace Hello; using namespace GoodBye; the above would present a problem ONLY when the function message() is called.
Test2 - Following is illegal: Code: using Hello::message; using GoodBye:: message;
this is probably the proof that using "using directive" is not same as multiple application of "using delcaration"s.
결국 질문은 using 지시자가 왜 using 선언을 여러번 적용한 것이랑 다른지, 어떻게 다른지 입니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
저는 using 선언한 것과 using 지시자 적용이 평소 이용측면에서는 차이점이 없다고 알고있습니다.
다만, 제가 알고 있는 using 지시자와 using 선언의 차이점에 대해 말씀드릴려고합니다.
Using 지시자(directive) : 지정한 네임스페이스의 모든 명칭을 이 선언이 있는 영역으로 가져와 소속 지정없이 명칭을 바로 사용할수있다. Ex) using namespace~
Using 선언자: ex) using std::cout;
Using 선언은 지역변수와의 명칭이 충돌할 경우 에러로 처리하는데 비해 (지역변수의 명칭과 Using의 명칭이 같을 경우 컴파일러가 구분을 하지 못합니다.)
Using 지시자는 네임스페이스의 명칭에 대한 가시성이 제한될 뿐 에러나 경고를 내지 않는다. (지역변수의 명칭과 using의 명칭이 같을 경우 컴파일러는 지역 내에서는 같은 명칭을 쓸 경우 지역변수로 인식합니다. Namespace의 명칭을 쓰기 위해서는 std::cout과 같은 형태로 써야합니다.)
언뜻 생각하기에 using 지시자가 더 관대한 것 같지만 사실 이런 상황이 골치 아픈 에러의 원인이 될 수 있습니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력