Programming/C++

[c++] Understanding of Reference

OKOK 2017. 5. 13. 23:00

#include <iostream>

using namespace std;


int main(void)

{

int num1 = 1020;

int &num2 = num1;


num2 = 3047;

cout << "VAL: " << num1 << endl;

cout << "REF: " << num2 << endl;


cout << "VAL: " << &num1 << endl;

cout << "REF: " << &num2 << endl;

return 0;

}



* num1 에 대한 참조자 num2를 선언하였다. 메모리 공간 생각하기

* 선언 생성 메모리 공간안에서 생각하기

* 이는 고정형이다. 선언 변수



#include <iostream>

using namespace std;


int main(void)

{

int arr[3] = { 1, 3, 5 };

int &ref1 = arr[0];

int &ref2 = arr[1];

int &ref3 = arr[2];


cout << ref1 << endl;

cout << ref2 << endl;

cout << ref3 << endl;

return 0;

}



* 배열이 아닌 배열의 요소를 변수로 간주하여 참조자의 선언이 가능하다.


#include <iostream>

using namespace std;


int main(void)

{

int num = 12;

int *ptr = &num;

int **dptr = &ptr;


int &ref = num;

int *(&pref) = ptr;

int **(&dpref) = dptr;


cout << ref << endl;

cout << *pref << endl;

cout << **dpref << endl;

return 0;

}


* 포인터 변수의 참조자 선언도 & 연산자를 하나 더 추가하는 형태로 진행

* pref 포인터 변수 ptr의 참조자

* dpref 는 포인터 변수 dptr 의 참조자