티스토리 뷰

LANGUAGE/C++

[C++] REFERENCE

진심스테이크 2018. 3. 5. 15:11

 

reference 변수 : 무조건 선언과 동시에 초기화 되어야 한다

- 닉네임 개념 -> 한번 선언하면 바꿀 수 없다

#include "stdafx.h"
#include <iostream>
using namespace std;

void main() {
    int a = 10;
    int b = 20;

    int &c = a; //reference 변수 : a를 c로 부름

    cout << &a << endl;
    cout << &b << endl;
    cout << &c << endl;

    cout << a << endl;
    cout << b << endl;
    cout << c << endl;

    c = 39;
    cout << a << endl; //39
    cout << b << endl;
    cout << c << endl;

    c = b; //b의 값을 가져옴 -> 한번 참조하면 바꾸질 못함
    cout << a << endl; //20
    cout << b << endl; //20
    cout << c << endl; //20
}

 


 

reference를 사용해서 함수 swap

#include "stdafx.h"
#include <iostream>
using namespace std;

void change(int &a, int &b);

void main() {
    int a = 10;
    int b = 20;
    
    change(a, b);
    cout << a << endl;
    cout << b << endl;
}

void change(int &a, int &b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}

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

[C++] DYNAMIC MEMORY - 동적 메모리  (0) 2018.03.06
[C++] POINTER - 포인터  (0) 2018.03.05
[C++] CALL BY  (0) 2018.03.05
[C++] ARRAY - 배열  (0) 2018.03.05
[C++] BASIC THINGS  (0) 2018.03.05
댓글