8.7 this 포인터와 연쇄 호출
#include <iostream>
using namespace std;
class Simple
{
private:
int m_id;
public:
Simple(int id)
{
//this->setID(id); 가 숨어있다.
setID(id);
cout << this << "\n"; // 자기 자신의 주소
}
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); // s1, s2 구분 ->
cout << &s1 << " " << &s2 << "\n";
//각 instance들이 자기의 포인터를 가지고 있고 this로 확인 가능.
return 0;
}
#include <iostream>
using namespace std;
class Calc
{
private:
int m_value;
public:
Calc(int init_value)
: m_value(init_value)
{}
// void add(int value) { m_value += value; }
// void sub(int value) { m_value -= value; }
// void mult(int value) { m_value *= 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 print()
{
cout << m_value << "\n";
}
}
int main()
{
Calc cal(10);
//cal.add(10);
//cal.sub(1);
//cal.mult(2); -> 번거롭다.
//cal.print();
cal.add(10).sub(10).mult(2).print(); // 자기 자신을 return 하기 때문에 연속해서 함수 작성 가능
return 0;
}