C++에서의 사용에 대한 빠른 소개

C++ 코드 조각을 작성한 적이 있다면 다음과 같은 특정 줄을 보았을 것이라고 예상합니다.

using namespace std;


'using은(는) 무슨 뜻인가요?'
using는 다음과 같은 경우에 적용할 수 있는 C++의 keyword입니다.

네임스페이스의 모든 구성원을 현재 범위로 가져옵니다.


using 지시문을 사용하면 네임스페이스의 모든 이름을 명시적 한정자로 namespace-name 없이 사용할 수 있습니다.

using namespace std; 
// brings all namespace names in the current scope
string my_string;
// std::string can now be referred as string throughout the scope

OR

std::string my_string; 
// string is now recognized, 
// however, will have to be addressed as std::string 
// wherever required


이제 using 다음에서 무엇을 하는지 알 수 있습니다.

using namespace std


범위에 namespace std를 가져오므로 명시적 접두사 없이 std에서 이름을 사용하는 것이 편리합니다std::.

If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is, therefore, a good practice to not bring complete namespaces in scope in long code files to avoid such cases where an intuitive identifier name has to be dropped 🙁 because same name exists in the namespace brought in scope by using. A workaround is to bring a specific name from a namespace in scope as:



using std::string;


기본 클래스 메서드 또는 변수를 현재 클래스의 범위로 가져옵니다.




class BaseClass {
   public:
      void sayHi() {
         cout << "Hi there, I am Base" << endl;;
      }
};

class DerivedClass : BaseClass {
   public:
      using Base::sayHi; 
      void sayHi(string s) {
         cout << "Hi, " << s << endl;
         // Instead of recursing, the greet() method
         // of the base class is called.
         sayHi();
      }
};


유형 별칭 만들기




template <typename T>
using MyName = MyVector<T, MyAlloc<T> >; 
MyName<int> p; // sample usage



using flags = std::ios_base::fmtflags;
// identical to 
// typedef std::ios_base::fmtflags flags;

typedef는 C++ 언어에 이미 존재하는데, 왜 using가 유형 별칭을 만들기 위해 도입되었는지 궁금합니다. 이것은 유효한 질문이고 흥미로운 질문입니다. 😄에서 읽을 수 있는 typedefusing 유형 별칭과 관련된 몇 가지 흥미로운 사실이 있습니다.

There are more caveats to using but are not covered here because this is a quick introduction, and also because of how rarely they are encountered. I encourage you to read more about using here.



이 글을 읽어주셔서 감사하고 다음 글에서 만나요 😄

PS: This is an article in my series Quick Introduction to a concept in C++. You can find all the articles in this series . I also answer why I don't use the series feature by there.

좋은 웹페이지 즐겨찾기