'reference variable'에 해당되는 글 1건

  1. 2010.09.15 C++ 레퍼런스 변수(reference variable) 4
Programming/C++ STL2010. 9. 15. 13:06
int& a;
요 &가 바로 레퍼런스 변수이다.
어떻게 보면 포인터와 비슷하지만, 다른 녀석이고, C++ 공부중에 함수 인자에서 혼동을 느끼게 한 녀석이다.

// more than one returning value
#include <iostream>
using namespace std;

void prevnext (int x, int& prev, int& next)
{
  prev = x-1;
  next = x+1;
}

int main ()
{
  int x=100, y, z;
  prevnext (x, y, z);
  cout << "Previous=" << y << ", Next=" << z;
  return 0;
}

[링크 : http://www.cplusplus.com/doc/tutorial/functions2/]
[링크 : http://www.cplusplus.com/doc/tutorial/pointers/]

위의 소스중, prevent() 함수의 두/세번째 인자가 바로 reference 변수인데,
C에서는 당연히 포인터로 넘겨주어야 할꺼라고 생각을 했는데,
C++에서는 변수를 그냥 인자로 취해줌에도 불구하고 원본의 값이 바뀐다.
(당연히.. 레퍼런스 변수란걸 모르니 이상하게 보일수 밖에 ㅠ.ㅠ)

처음에는 자동형변환과 연관이 되어있나 했는데.. 그거랑은 거리가 좀 있는것 같고
그냥 단순히 C++ 문법적 특성으로 "참조형 변수" 라고 생각중 -_-

C++ 참조와 포인터의 차이점
- 만들어지면 값 변경불가
- 위의 이유로 null로 선언불가

C++ references differ from pointers in several essential ways:

  • It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
  • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  • References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
  • References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor. For example:

[링크 : http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29]

[링크 : http://hijacker.egloos.com/1379523]
[링크 : http://www.cprogramming.com/tutorial/references.html]



'Programming > C++ STL' 카테고리의 다른 글

new / new[] / delete / delete[]  (4) 2010.09.16
cout 그리고 namespace  (0) 2010.09.16
C++0x  (0) 2010.09.15
std::vector 포인터  (0) 2010.09.13
스마트 포인터(smart pointer)  (2) 2010.09.09
Posted by 구차니