본문 바로가기

IT 관련자료/C++

this 포인터와 연쇄호출

#include <iostream>

using namespace std;

class Simple
{
private:
    int _id;

public:
    Simple(int id)
    {
        setID(id);
        //this는 자기 자신을 가리키는 포인터
        cout << this << endl;
        //
        //현재 주소를 가지고 있는 인스턴스에서 setID라는 함수를 접근한다는 의미
        this->setID(id);
        this->_id;
    }

    void setID(int id) { _id = id; }
    int getID() { return _id; }
};

class Calc
{
private:
    int _value;

public:
    Calc(int init_value)
        :_value(init_value)
    {
        cout << this << endl;
    }
    

    void add(int value) { _value += value; }
    void sub(int value) { _value -= value; }
    void mult(int value) { _value *= value; }

    void print()
    {
        cout << _value << endl;
    }

};
int main()
{
    Calc cal(10);
    cal.add(10);
    cal.sub(1);
    cal.mult(2);

    cal.print();




    Simple s1(1), s2(2);
    //s1,s2에 각각 함수가 들어가 있을까???
    //각각을 메모리에 다 할당해주는게 아니라...
    //Simple::setID(&s1,1); 이런식으로 쓴다고 생각(실제로는 문법상 못쓰지만 레퍼런싱 변수저장 하는것 처럼!!쓴다)
    //s1.setID(1)만 되지만... 개념상으로 저렇다고 이해하자

    s1.setID(2);
    s2.setID(4);

    cout << &s1 << " " << &s2 << endl;

    return 0;
}

'IT 관련자료 > C++' 카테고리의 다른 글

클래스와 const  (0) 2022.02.25
클래스코드와 헤더파일  (0) 2022.02.25
소멸자(생성자 (constructor)의 반대개념)  (0) 2022.02.24
위임생성자  (0) 2022.02.24
객체지향 기본개념 정리코드  (0) 2022.02.24