C++ 포인터 && this && chaining 기법

이번엔 포인터에 대한 실습을 해보았고 그릴 통해서 chaining 기법을 이용해서 라인 수를 줄이는 실습을 해보았다

#include <iostream>

using namespace std;

class Simple
{
private:
    int m_ID;

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

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

    int GetID()
    {
        return m_ID;
    }
};

class Simple2
{
private:
    int data;
public:
    Simple2(int data)
    {
        this->data = data; // 멤버 변수를 this를 통해 식별함으로서 멤버변수와 매개변수를 구분 하는 것이 가능하다.
                           // 하지만 사실은 멤버변수는 m_data를 이용해서 분리하는것이 바람직하다.
    }

};

class Calc
{
private:
    int m_Value = 0;
public:
    void Add(int value){m_Value += value;}
    void Sub(int value){m_Value -= value;}
    void Mul(int value){m_Value *= value;}

    int GetValue(){return m_Value;}
};

class Calc2 //Chaining 기법을 위한 방법이다. this를 이용해서 포인터에 인수를 지정해줌으로서 chaining 기법을 이용할 수 있다.
{
private:
    int m_Value = 0;
public:
    Calc2& Add(int value){m_Value += value; return *this;}
    Calc2& Sub(int value){m_Value -= value; return *this;}
    Calc2& Mul(int value){m_Value *= value; return *this;}

    int GetValue(){return m_Value;}
};



int main()
{
    Simple simple(1);
    Simple A(1);  //Simple(&A,1); -> constructor 내부의 this = &A가 된다.
    Simple B(2);  //SImple(&B,2); -> constructor 내부의 this = &B가 된다.
    simple.SetID(2);
    A.SetID(3); //SetID(&A,3); -> 멤버함수 SetID 내부 this = &A이다.
    B.SetID(4); //SetID(&B,4); -> 멤버함수 SetID 내부 this = &B이다.

    cout<<simple.GetID()<<endl;

    Calc2 calc;
    calc.Add(10).Mul(2).Sub(13).Add(10);
   
    cout<<calc.GetValue()<<endl;

    return 0;
}

////
// simple.SetID(2); 는 결국 simple.SetID(&simple, 2); 로 형변환이 되는 것이다.
// 이를 통해 &simple의 인스턴스에 value를 변경해주게 된다.
////
// void SetID(int id){ m_ID = id; } 는
//void SetID(Simple* const this, int id)
//{ this->m_ID = id; }
//라는 형식으로 변환 되는 것이다. 이를 통해 이 인스턴스의 value를 변환한다는 것을 알 수 있다.
//결과적으로 this->m_ID 는 simple->m_ID와 동일하다.
////
//this 함수는 매개변수이기 때문에 메모리에 영향을 주지 않는다.


댓글

이 블로그의 인기 게시물

About AActor!!! "UObject" has no member "BeginPlay"

UNREAL Android build information

C++ 생성자 위임 (delegating constructor)