20141010 (C++ this)
155일차
-------------
C++
-------------
------- this
현재 객체를 가리킨다
(객체 주소)
예제)
#include <iostream>
#include <cstring>
using namespace std;
class SoSimple
{
public:
int num;
public:
SoSimple(int n)
: num(n)
{
cout << "num=" << num << ", ";
cout << "address=" << this << endl;
}
void ShowSimpleData()
{
cout << num << endl;
}
SoSimple * GetThisPointer()
{
return this;
}
};
int main()
{
SoSimple sim1(100);
SoSimple * ptr1 = sim1.GetThisPointer();
cout << ptr1 << ", ";
ptr1->ShowSimpleData();
SoSimple sim2(200);
SoSimple * ptr2 = sim2.GetThisPointer();
cout << ptr2 << ", ";
ptr2->ShowSimpleData();
return 0;
}
결과
다른 예제)
#include <iostream>
using namespace std;
class SelfRef
{
private:
int num;
public:
SelfRef(int n)
: num(n)
{
cout << "객체생성" << endl;
}
SelfRef & Adder(int n)
{
num = num + n;
return *this;
}
SelfRef & ShowTwoNumber()
{
cout << num << endl;
return *this;
}
};
int main()
{
SelfRef obj(3);
SelfRef & ref = obj.Adder(2);
obj.ShowTwoNumber();
ref.ShowTwoNumber();
ref.Adder(1).ShowTwoNumber().Adder(2).ShowTwoNumber();
return 0;
}
결과
--------------
RFID
--------------