# this 포인터

## this 포인터 <a href="#this-ed-8f-ac-ec-9d-b8-ed-84-b0" id="this-ed-8f-ac-ec-9d-b8-ed-84-b0"></a>

클래스 내부에서 `this`를 사용하여 자기 자신을 참조하는 포인터이다.

**this포인터를 활용한 예제**

```cpp
#include <iostream>
using namespace std;

class Point {
  int x;
  int y;
public :
  Point(int x = 0, int y = 0) : x(x), y(y) {
    cout << "객체 생성" << endl;
   }

  void add(int x, int y = 0) {
    this->x += x;
    this->y += y;
  }

  void show() {
    cout << "[" << x << "," << y << "]" << endl;
  }
};

int main() {
  Point p1(10, 50);
  Point p2(20);

  p1.add(20, -10);
  p2.add(5, 23);
  p1.show();
  p2.show();
}
```

## 자기 자신 참조자(Self Reference) 반환 <a href="#ec-9e-90-ea-b8-b0-ec-9e-90-ec-8b-a0-ec-b0-b8-ec-a1-b0-ec-9e-90self-reference-eb-b0-98-ed-99-98" id="ec-9e-90-ea-b8-b0-ec-9e-90-ec-8b-a0-ec-b0-b8-ec-a1-b0-ec-9e-90self-reference-eb-b0-98-ed-99-98"></a>

&#x20;this포인터가 가리키는 값을 반환하여 참조자를 반환할 수 있다.

```cpp
#include <iostream>
using namespace std;

class Point {
  int x;
  int y;
public :
  Point(int x = 0, int y = 0) : x(x), y(y) { 
    cout << "객체 생성" << endl;
  }

  Point& add(int x, int y = 0) {
    this->x += x;
    this->y += y;
    return *this;
  }

  Point& show() {
    cout << "[" << x << "," << y << "]" << endl;
    return *this;
  }
};

int main() {
  Point p1(10, 50);
  Point& p2 = p1.add(10, -10);

  p1.show();
  p2.show();

  p1.add(15, 15).show().add(-3, -17).show();
  p2.show();
}
```

&#x20;반환형이 `Point&`이고 이렇게 `return *this;`로 반환하면 참조자 정보를 반환한다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ezcode.gitbook.io/bnb-cpp/class/this.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
