특징
this 포인터는 자동적으로 시스템이 만들어 주는 포인터 멤버가 호출될 때 그 멤버가 속한 객체를 가르킨다. 객체를 통하여 멤버를 호출할 때 컴파일러는 객체의 포인터 즉 주소를 this포인터에 넣은 다음 멤버를 호출한다. this 포인터는 멤버를 호출한 객체의 const 포인터이다. 멤버함수에서 볼 때 this 포인터는 어떤 객체가 자신을 호출했는지 알고자 하는 경우 사용한다. 클래스의 멤버함수 내에서 다른 클래스에 자기 자신을 매개변수로 넘길 때 사용
this 포인터 예 1
#include <iostream> using std::cout; class Dog { private: int age; public: Dog(int a) { this->age = a; } ~Dog() { cout << "소멸"; } int getAge(); void setAge(int a); }; int Dog::getAge() { return this->age; } void Dog::setAge(int a) { this->age = a; } int main() { Dog happy(5); cout << happy.getAge(); return 0; }
<this 포인터 예 2>
#include <iostream> using std::cout; using std::endl; class Dog { private: int age; public: Dog(int a); ~Dog(); int getAge(); void setAge(int a); }; Dog::Dog(int a){ age = a; cout << this << endl; } Dog::~Dog(){ cout << "소멸"; } int Dog::getAge(){ return age; } void Dog::setAge(int a){ age = a; } int main(){ Dog happy(5), meri(3); cout << happy.getAge(); cout << meri.getAge(); return 0; }