참조 변수 reference

강형우·2022년 12월 13일
0

C++

목록 보기
8/10
post-thumbnail

참조 변수 &

  • ref는 value의 별명처럼 사용될 수 있다.
int value = 5;
int &ref = value;
cout << ref << endl; // 5출력
ref = 10; // *ptr = 10 과 같이 작동
cout << value << " " << ref << endl; // 10 10 출력

int *ptr = nullptr;
ptr = &value;
cout << &value << endl; // 004FF864
cout << &ref << endl; // 004FF864 주소값이 완전히 value와 똑같다. 
cout << ptr << endl; // 004FF864
cout << &ptr << endl; // 004FF858 // 포인터는 포인터 자체의 주소를 갖는다

reference와 const

int value = 5;
int &ref; // ❌ 에러! &는 선언과 동시에 초기화가 이루어져야함
int &ref = 104 // ❌ 에러! L-value가 들어갈 수 있다.
int &ref = x // ✔️
const int y = 8;
int &ref = y; //❌ 에러! ref에서 y값을 마음대로 바꿀 수 있기 때문에 안된다.
const int &ref = y; ✔️ 앞에 const를 붙이면 가능

reference의 reassign

int value1 = 5;
int value2 = 10;

int &ref1 = value1;

cout << ref1 << endl; // ✔️ 5출력
ref1 = value2;
cout << ref1 << endl; // ✔️ 10출력

reference의 인자 전달

  • reference를 쓰지 않을때
#include<iostream>

using namespace std;

void dofunc(int n)
{
	n = 10
    cout << "In dofunc" << n << endl;
}

int main()
{
	int n = 5;
    cout << n << endl;
    dofunc(n);
    cout << n << endl;
    return 0;
}

5
In dofunc 10
5

  • reference를 사용할 때
#include<iostream>

using namespace std;

void dofunc(int &n)
{
	n = 10
    cout << "In dofunc" << n << endl;
}

int main()
{
	int n = 5;
    cout << n << endl;
    dofunc(n);
    cout << n << endl;
    return 0;
}

5
In dofunc 10
10

array에서의 참조


void dofunc(const int &n)
{
// 입력으로 받는 인자값을 바꾸는것을 금지할때
	n = 10 //❌ 에러!
    cout << "In dofunc" << n << endl;
}

void printElements(int (&arr)[5])
{
	for(int i = 0; i < 5; i++)
    
    {
    	cout << arr[i] << " ";
    }
}
int main()
{
	// array를 함수에 넣어줄때도 reference를 사용할 수 있다.
	const int length = 5;
    int arr[length] = {1,2,3,4,5};

}

const 와 ptr

int value = 5;
int *const ptr = &value;
int &ref = value;

*ptr = 10; ✔️
ref = 10; ✔️
// 두 개가 동일하게 작동하는것을 볼 수 있다.

&ref도 내부적으로는 포인터로 구성이 되어있다.

0개의 댓글