#include <iostream>
using namespace std;
class Circle {
int radius;
public:
Circle() { radius = 1; cout << "생성자 실행" << endl; }
Circle(int radius) { this->radius = radius; cout << "생성자 실행" << endl;
}
~Circle() { cout << "소멸자 실행" << endl; }
int getRadius() { return radius; }
void setRadius(int radius) { this->radius = radius; }
};
int main() {
Circle waffle(30);
Circle& maybe_waffle = waffle;
cout << waffle.getRadius() << " " << maybe_waffle.getRadius() << endl;
int i = 2020270127;
int& maybe_i = i;
maybe_i -= 2020;
cout << i << " " << maybe_i;
}
참조변수는 어떠한 메모리 공간을 차지하는 변수나 클래스 등의 '닉네임'을 정해 또 다른 접근 방법을 제공한다.
#include <iostream>
using namespace std;
bool average(int a[], int size, int& avg) {
if (size <= 0)
return false;
int sum = 0;
for (int i = 0; i < size; i++)
sum += a[i];
avg = sum / size;
return true;
}
int main() {
int x[] = { 0,1,2,3,4,5 };
int avg;
if (average(x, 6, avg))
cout << "평균은 " << avg << endl;
else cout << "매개변수 오류다 이거야 " << endl;
if (average(x, -2, avg))
cout << "평균은 " << avg << endl;
else cout << "매개변수 오류다 이거야 " << endl;
}
메모리 공간을 공유하기 때문에, 다음 코드와 같이 값을 계산함과 동시에 할당할 수 있다. 객체를 할당할때 용이하다.
#include <iostream>
using namespace std;
char c = 'a';
char& r() {
return c;
}
char* p() {
return &c;
}
int main() {
char* s = p();
*s = 'b';
//p() = 'b'; 컴파일 오류 (주소값에 바로 넣어줄 수 없음)
r() = 'c';
}
c언어에선 다음과 같이 참조 역할을 만들 수 있지만, 본연의 의도와 달리 코드가 더 복잡해진듯 하다.