logo

C++의 'this' 포인터

'this' 포인터를 이해하려면 객체가 클래스의 함수와 데이터 멤버를 어떻게 보는지 아는 것이 중요합니다.

  1. 각 개체는 데이터 멤버의 자체 복사본을 가져옵니다.
  2. 코드 세그먼트에 있는 것과 동일한 기능 정의에 모두 액세스합니다.

즉, 각 개체는 자체 데이터 멤버 복사본을 가지며 모든 개체는 멤버 함수의 단일 복사본을 공유합니다.
그렇다면 이제 질문은 각 멤버 함수의 복사본이 하나만 존재하고 여러 개체에서 사용되는 경우 적절한 데이터 멤버에 어떻게 액세스하고 업데이트합니까?
컴파일러는 함수 이름과 함께 'this'라는 암시적 포인터를 제공합니다.
'this' 포인터는 모든 비정적 멤버 함수 호출에 숨겨진 인수로 전달되며 모든 비정적 함수 본문 내에서 지역 변수로 사용할 수 있습니다.정적 멤버 함수는 개체 없이(클래스 이름 포함) 호출될 수 있으므로 'this' 포인터는 정적 멤버 함수에서 사용할 수 없습니다.
클래스 X의 경우 이 포인터의 유형은 'X*'입니다. 또한 X의 멤버 함수가 const로 선언되면 이 포인터의 유형은 'const X *'입니다(이 GFact 참조).



C++의 초기 버전에서는 'this' 포인터를 변경할 수 있었습니다. 그렇게 함으로써 프로그래머는 메소드가 작업 중인 객체를 변경할 수 있습니다. 이 기능은 결국 제거되었으며 이제 C++에서는 r-값이 됩니다.
C++에서는 다음 코드를 호출하여 객체가 스스로 파괴되도록 합니다.








delete> this>;>

>

>

Java의 간단한 날짜 포맷터

Stroustrup이 말했듯이 'this'는 포인터가 아닌 참조일 수 있지만 C++의 초기 버전에는 참조가 없었습니다. 'this'를 참조로 구현하면 위의 문제를 피할 수 있으며 포인터보다 안전할 수 있습니다.

다음은 'this' 포인터가 사용되는 상황입니다.

1) 로컬 변수 이름과 멤버 이름이 동일한 경우




종교 목록

#include> using> namespace> std;> > /* local variable is same as a member's name */> class> Test> {> private>:> >int> x;> public>:> >void> setX (>int> x)> >{> >// The 'this' pointer is used to retrieve the object's x> >// hidden by the local variable 'x'> >this>->x = x;> >}> >void> print() { cout <<>'x = '> << x << endl; }> };> > int> main()> {> >Test obj;> >int> x = 20;> >obj.setX(x);> >obj.print();> >return> 0;> }>

>

>

산출:

 x = 20>

생성자의 경우, 초기화 목록 매개변수 이름이 멤버 이름과 동일한 경우에도 사용할 수 있습니다.



2) 호출 객체에 대한 참조를 반환하려면




/* Reference to the calling object can be returned */> Test& Test::func ()> {> >// Some processing> >return> *>this>;> }>

>

>

로컬 객체에 대한 참조가 반환되면 반환된 참조를 사용하여 체인 함수 호출 단일 개체에.

리눅스 파일 시스템이 뭐야?




#include> using> namespace> std;> > class> Test> {> private>:> >int> x;> >int> y;> public>:> >Test(>int> x = 0,>int> y = 0) {>this>->x = x;>this>->y = y; }> >Test &setX(>int> a) { x = a;>return> *>this>; }> >Test &setY(>int> b) { y = b;>return> *>this>; }> >void> print() { cout <<>'x = '> << x <<>' y = '> << y << endl; }> };> > int> main()> {> >Test obj1(5, 5);> > >// Chained function calls. All calls modify the same object> >// as the same object is returned by reference> >obj1.setX(10).setY(20);> > >obj1.print();> >return> 0;> }>

>

>

산출:

x = 10 y = 20>



운동:
다음 프로그램의 출력을 예측해 보세요. 컴파일 오류가 있으면 수정하세요.

질문 1




#include> using> namespace> std;> > class> Test> {> private>:> >int> x;> public>:> >Test(>int> x = 0) {>this>->x = x; }> >void> change(Test *t) {>this> = t; }> >void> print() { cout <<>'x = '> << x << endl; }> };> > int> main()> {> >Test obj(5);> >Test *ptr =>new> Test (10);> >obj.change(ptr);> >obj.print();> >return> 0;> }>

>

자바 시각화 장치
>



질문 2




#include> using> namespace> std;> > class> Test> {> private>:> >int> x;> >int> y;> public>:> >Test(>int> x = 0,>int> y = 0) {>this>->x = x;>this>->y = y; }> >static> void> fun1() { cout <<>'Inside fun1()'>; }> >static> void> fun2() { cout <<>'Inside fun2()'>;>this>->fun1(); }> };> > int> main()> {> >Test obj;> >obj.fun2();> >return> 0;> }>

>

>



질문 3




#include> using> namespace> std;> > class> Test> {> private>:> >int> x;> >int> y;> public>:> >Test (>int> x = 0,>int> y = 0) {>this>->x = x;>this>->y = y; }> >Test setX(>int> a) { x = a;>return> *>this>; }> >Test setY(>int> b) { y = b;>return> *>this>; }> >void> print() { cout <<>'x = '> << x <<>' y = '> << y << endl; }> };> > int> main()> {> >Test obj1;> >obj1.setX(10).setY(20);> >obj1.print();> >return> 0;> }>

>

>

자바의 인스턴스



질문 4




#include> using> namespace> std;> > class> Test> {> private>:> >int> x;> >int> y;> public>:> >Test(>int> x = 0,>int> y = 0) {>this>->x = x;>this>->y = y; }> >void> setX(>int> a) { x = a; }> >void> setY(>int> b) { y = b; }> >void> destroy() {>delete> this>; }> >void> print() { cout <<>'x = '> << x <<>' y = '> << y << endl; }> };> > int> main()> {> >Test obj;> >obj.destroy();> >obj.print();> >return> 0;> }>

>

>