250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/8.7] this 포인터와 연쇄호출, pointer and chaining member function 본문

C++/따배C++ 08강 객체지향 기초

[C++/8.7] this 포인터와 연쇄호출, pointer and chaining member function

polarcompass 2021. 10. 22. 03:34
728x90

1. this 포인터 (포인터 주소 확인)

#include<iostream>
using namespace std;

class Simple
{
private:
    int m_id;
public:
    Simple(int id)
    {
        // this 는 s1의 포인터 주소.
        setID(id);

        cout << this << endl;
    }

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

int main()
{
    Simple s1(1), s2(2);
    s1.setID(2);
    s2.setID(4);

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

    // Simple::setID(&s2, 4); == s2.setID(4);

    return 0;
}

2. 연쇄호출

#include<iostream>
using namespace std;

class Calc
{
private:
    int m_value;
public:
    Calc(int init_value)
        : m_value(init_value)
    {}

    Calc& add(int value) { m_value += value; return *this;}
    Calc& sub(int value) { m_value -= value; return *this;}
    Calc& mult(int value) { m_value *= value; return *this;}
    // void div(float value) { m_value /= value; }

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

int main()
{
    Calc cal{10};
    cal.add(10).sub(1).mult(2).print();
    // cal.add(10);
    // cal.sub(1);
    // cal.mult(2);
    
    // cal.print();
    Calc &temp1 = cal.add(10);
    Calc &temp2 = temp1.sub(1);
    Calc &temp3 = temp2.mult(2);
    temp3.print();

    return 0;
}
728x90