Computer Science/C & C++

[C++] this Pointer | this 포인터

lww7438 2020. 2. 26. 22:50

\(\texttt{this}\) Pointer

\(\texttt{this}\) 포인터

- 클래스 객체와 관련이 있는 포인터이다.
- \(\texttt{this}\) 포인터는 멤버 함수를 호출한 객체 "자기 자신"을 지시하는 포인터이다.
- 기본적으로, \(\texttt{this}\)는 해당 메서드에 숨은 매개변수로써 프로그래머가 모르게 전달된다.
(모든 클래스 메서드들은 호출한 객체의 주솟값을 가진 하나의 \(\texttt{this}\) 포인터를 가진다.)
- \(\texttt{this}\) 포인터는 특히, 하나의 메서드가 두 개의 데이터 객체를 동시에 처리할 때 유용하게 쓰인다.

// Ex. this 포인터의 약식 표기 예시

class Person {
private:
    std::string name;
    int m_height;
    double m_weight;
Public:
    Person(string&, int, double);
    ...
};

Person::Person(strong& n, int h, double w) {
    name = n;      // (this->name) = n;의 약식 표기
    m_height = h;  // (this->m_height) = h;의 약식 표기
    m_weight = w;  // (this->m_weight) = w;의 약식 표기
}