티스토리 뷰

typedef class _cTest{
private:
 int a;
 int b;

public:
 void set_a(int i)
 {
  a = i;
 }
 void print_a()
 {
  cout << a << endl;
 }

} cTest, *kTest;

typedef cTest* pTest;

cTest test_f(cTest);
kTest ptest_f(kTest);


int _tmain(int argc, _TCHAR* argv[])
{
 cTest test;
 pTest ptest;

 ptest = &test; //반드시 선행돼야한다. 이게 없으면 ptest는 껍데기일 뿐이다. 이 시행을 해준 덕분에 ptest를 조작하면 test의 값도 변경된다.


 cout << "default" << endl;
 test.set_a(3);
 test.print_a();

 cout << "func call" << endl;
 test_f(test);

 cout << "after func call" << endl;
 test.print_a(); //바뀌지 않음

 cout << "pdefault" << endl;
 ptest->set_a(3);
 ptest->print_a();

 cout << "pfunc call" << endl;
 ptest_f(ptest);

 cout << "after pfunc call" << endl;
 ptest->print_a(); //바뀜

 cout << "what is the test value?" << endl;
 test.print_a(); //test의 값이 바껴있다.

 return 0;
}

cTest test_f(cTest test)
{
 test.set_a(4);
 test.print_a();

 return test;
}


pTest ptest_f(pTest ptest)
{
 ptest->set_a(4);
 ptest->print_a();
 
 return ptest;
}






코드를 보면 똑같은 타입을 일부로 이것저것 막 적어놓았는데(kTest와 pTest는 동일합니다)

typedef class _cTest{
private:
 int a;
 int b;

public:
 void set_a(int i)
 {
  a = i;
 }
 void print_a()
 {
  cout << a << endl;
 }

} cTest, *kTest;

이부분은 사실

class cTest{
private:
 int a;
 int b;

public:
 void set_a(int i)
 {
  a = i;
 }
 void print_a()
 {
  cout << a << endl;
 }

};

typedef cTest* kTest; 이렇게 바꿔줘도 전혀 상관이 없습니다.
하지만 클래스를 생성하면서 한번에 포인터형도 선언해 준다니~ 얼마나 편합니까 ㅎㅎ
웬만하면 클래스 생성할때 typedef로 하여서 포인터 형도 함께 선언합시다~ㅎㅎ

코드의 결과는 예상하신대로입니다.
포인터형 클래스(구조체) 호출 뒤에는 main에서도 값이 변경된답니다.

뱀발) 이런것도 먹힌다는거~
typedef int in, *pin;
in ti = 3;
pin pti = &ti;
cout << ti << endl;
*pti = 8;
cout << ti << endl;

포인터를 쓰는 주된 이유중 하나는 이함수 저함수 불려갔다가 나오면 값이 적용되어 나오도록 해주기 위함이겠죠? 물론 전역으로 해주어도 되겠지만 메모리 관리의 효율성을 위하여..

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함