@ 16. 1 ~ 17. 1/C++

멤버 함수가 객체 자신을 리턴하는 경우

namoeye 2014. 10. 27. 22:29

#include<iostream>
#include<conio.h>
#include"SparseGraph.h"
#include<math.h>

using namespace std;

class CTest
{
public:
 int i;
 CTest()
 {
  i=100;
 }
 void Print();
 CTest MySelf();

//CTest& MySelf();
};

void CTest::Print()
{
 cout << this->i << endl;
}

CTest CTest::MySelf()
{
 ++i;
 return *this;
}

int main()
{

 CTest t;
 //t.MySelf();
 //t.Print();

 t.MySelf().Print(); //myselft()가 객체를 리턴하므로 가능하다.
 t.MySelf().i=100; //오류가 난다

 getch();
 return 0;
}

 

오류가 나는 이유는

LValue 자리에는 항상 주소로 표현할 수 있는 값이 와야 한다는 것이다.

그러면 오류를 수정하려면.. myselft()가 리턴하는 값이 주소로 번역되도록 허용하는 것뿐이다.

myself()함수의 반환값을 CTest& 즉, 참조를 리턴하게 하면 된다..

(포인터로 할 경우 CTest* 반환값 하고 멤버함수내에서 return this하고 t.MySelf()->i=200; 이런식으로 해도..)