C++
[C++] this 포인터
SWBlossom
2019. 12. 15. 16:55
this 포인터란?
this 포인터는 작성 중인 클래스의 실제 인스턴스에 대한 주소를 가리키는 포인터이다. 즉, 객체가 자기 자신을 가리키는 포인터이다.
#include <iostream>
using namespace std;
class myClass
{
public:
myClass(int x, int y) {
this->x = x;
this->y = y;
}
void Print() {
cout << x << endl;
cout << y << endl;
}
private:
int x; //this->x
int y; //this->y
};
int main()
{
int x = 10;
myClass a(10, 20);
myClass b(30, 40);
a.Print();
b.Print();
return 0;
}
결과값:
10
20
30
40
this 포인터는 객체 자신을 가리키므로 예제에서 this 포인터가 빠진다면 매개변수x, y에 매개변수 x, y를 넣는 무의미한 코드가 될 것이다. 정작 사용하고 싶은 멤버변수 x, y에는 쓰레기값이 그대로 있을 것이다.
a.Print()는 a.Print(&a)를 b.Print()는 b.Print(&b)를 의미한다고 봐도 무방하다.