참조

참조 에서 C++

1개의 연습 문제

참조 소개

복사와 참조

지금까지 배운 내용만으로는 함수의 도움을 받아 변수를 갱신하는 게 조금 번거로워요. 함수의 인자는 모두 복사본처럼 다뤄져서 원래 값은 바뀌지 않아요. 타입의 크기에 따라 이 점이 코드 성능에 심각한 영향을 줄 수도 있어요.

int adjust_salary(int base, int kids) {
    return base + kids * 500;
}
int now_a_mother_of_twins{2500};
adjust_salary(now_a_mother_of_twins, 2);

// now_a_mother_of_twins is still 2500
now_a_mother_of_twins = adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is now 3500

References는 별칭으로 볼 수 있어요. 여기에 변경을 가하면 원래 변수에도 영향을 줘요. References는 타입 선언에서 앰퍼샌드(&)를 사용해요.

int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;

다시 연결하기 (reference의 바인딩을 바꾸는 것)는 불가능해요. 초기화되지 않은 reference는 만들 수 없어요. References는 이미 존재하는 변수로 초기화해야 해요.

int main_acc{1'000'000};
int side_acc{-20};
int& savings{main_acc};
// => main_acc and savings are 1'000'000

// try to reseat savings to use main account
savings = side_acc;
// savings and main_acc are now -20
// as this uses the **value** of side_acc
savings += 20;
// savings and main_acc are now 0, side_acc is stil -20

int& future_budget;
// => compiler error, reference must be bound!

void

references를 활용하면 함수에서 값을 반환할 필요가 아예 없을 수도 있어요. 이런 경우에는 void를 반환 타입으로 사용해요.

void increase_power(int& level) {
    level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!
GitHub에서 편집 링크가 새 창이나 탭에서 열려요

참조 배우기