int num1 = 2025;
-> 변수 선언을 통해 2025로 초기화 된 메모리 공간에 num1이라는 이름 붙음
int &num2 = num1;
-> num1이라는 이름이 붙어있는 메모리 공간에 num2라는 이름이 하나 더 붙음
주소값 나타내는 & 주소연산자와 전혀 다른 의미로 사용
이미 선언된 변수 앞에 & 연산자 오면 주소값 반환
새로 선언되는 변수 이름 앞에 오면 참조자 선언
ex)
int *ptr = &num1; // 변수 num1의 주소값 반환해서 포인터 ptr에 저장
int &num2 = num1; // 변수 num1에 대한 참조자 num2 선언
-> num2는 num1의 참조자
ex)
num2 = 2025;
-> 변수 num1의 메모리 공간에 2025 저장됨.
ex)
cout << num1 << endl;
cout << num2 << endl;
-> 결과 :
2025
2025
int num1 = 2025;
int &num2 = num1;
int &num3 = num1;
int &num4 = num1;
-> 하나의 메모리 공간에 num1, num2, num3, num4 이름 붙임
int num1 = 2025;
int &num2 = num1;
int &num3 = num2;
int &num4 = num3;
int &ref = 20 // 안 됨
int &ref; // 안 됨
int &ref = NULL // NULL로 초기화도 안 됨
int arr[3] = { 1, 3, 5 };
int &ref1 = arr[0];
int &ref2 = arr[1];
int &ref3 = arr[2];
int num = 10;
int *pnum = #
int **dpnum = &pnum;
int &ref = num;
int *(&pref) = pnum;
int **(&dpref) = dpnum;
-> ref, *pref, **dpref 모두 12
/*
다른 함수에 선언된 local변수의 값 바꾸는 방법
*/
#include <iostream>
using namespace std;
void chFunc(int* _n) {
*_n = 20;
}
int main()
{
int n = 10;
cout << "호출 전 n: " << n << endl;
chFunc(&n);
cout << "호출 후 n: " << n << endl;
return 0;
}
/*
다른 함수에 선언된 지역변수의 값을 바꾸는 방법2
레퍼런스 - 또다른 이름. 보이지 않는 포인터
*/
#include <iostream>
using namespace std;
void chFunc(int& rn) { // 레퍼런스(참조변수)선언
rn = 20;
}
int main()
{
int n = 10;
cout << "호출 전 n: " << n << endl;
chFunc(n);
cout << "호출 후 n: " << n << endl;
return 0;
}
/*
레퍼런스 - 선언과 동시에 초기화해야함
*/
#include <iostream>
using namespace std;
int main()
{
int num = 10, num2 = 100;
int& ref = num; // num의 메모리 공간에 ref라는 별명이 붙음.
int* pn = # // 포인터 선언
int& rref = ref;
rref = num2;
cout << rref << ", " << num2 << endl;
//int& rref; // 10열과 같이 초기화 하여야 함
//rref = ref;
num++;
ref++;
(*pn)++;
cout << "num++: " << num << endl;
cout << "ref++: " << ref << endl;
cout << "*(pn)++: " << *pn << endl;
cout << "&num: " << &num << endl; //아래줄과 동일한 주소값을 가짐
cout << "&ref: " << &ref << endl;
return 0;
}