C++ this포인터와 Cascaded Function Calls

Joosi_Cool·2022년 9월 25일
2

C++

목록 보기
12/20
post-thumbnail

this 포인트란?

this 포인터는 멤버함수가 호출된 객체의 주소를 가리키는 숨겨진 포인터이다.

class Simple
{
private:
    int m_ID;

public:
    Simple(int id)
    {
        SetID(id);
    }

    void SetID(int id)
    {
        m_ID = id;
    }

    int GetID()
    {
        return m_ID;
    }
};

int main(){
	Simple simple(5);
    
    simple.setId(10);
    
    cout<<simple.GetID();

}
// 출처: https://boycoding.tistory.com/250 [소년코딩:티스토리]

위의 예시 코드가 있다고 가정하자.
simple.setId(10); 의 경우, 숨겨진 포인터가 존재한다.

simple.setId(&simple,10);

즉, 멤버함수에 클래스 변수에 주소값이 들어간 것이다.

클래스 멤버의 경우에는 아래와 같이 변환된다.
여기서 this 포인터는 멤버 함수가 호출된 객체의 주소를 가리키는 숨겨진 포인터이다.

void SetID(Simple* const this,int id)
{
this->m_ID = id;
};

이렇듯 모든 멤버 함수는 함수가 호출된 객체를 가리키는 this 포인터를 가지고 있다.

this 포인터 사용 용도

  1. 멤버 변수와 이름이 같은 매개 변수를 가진 생성(또는 멤버함수)가 있는 경우 this를 통해 구분 가능.
class Something
{
private:
    int data;

public:
    Something(int data)
    {
        this->data = data;
        // this->data는 멤버 변수이고,
        // data는 매개 변수
    }
};
출처: https://boycoding.tistory.com/250 [소년코딩:티스토리]

하지만 이는 멤버 이니셜 라이져로 해결 가능하다.


  1. Cascaded Function Calls(멤버함수 체이닝 기법)
#include<iostream>
using namespace std;
class example {
private:
	int num;
public:

	example(int i) {
		num = i;
	}

	example& Add(int value){
		num += value;
		return *this;
	}
	example& Sub(int value) {
		num -= value;
		return *this;
	}
	example& Mul(int value) {
		num *= value;
		return *this;
	}

	int getValue() {
		cout << num;
		return num;
	}
	};
int main() {
	
	example ex(5);

	ex.Add(5).Sub(3).Mul(10).getValue();

	return 0;
};

각각의 멤버함수는 *this를 반환한다.
그럼에 따라 자기 자신(인스턴스)를 반환한다.
멤버함수에선 그 주소에 해당되는 클래스 변수에 값을 바꾼 후에 그 주소를 또 반환하며 위와 같은 Cascaded Function Calls 이 가능해진다.

profile
집돌이 FE개발자의 노트

0개의 댓글