문제

두 수를 입력 받아서 swap(두 개의 값을 바꾸는 기능의 함수)함수를 작성해보자.

(두 가지 방법 '포인터', '레퍼런스'를 이용하여 구현)

 

 

결과물

 

 

해설

swap 두 함수를 만들었습니다.

하지만 하나는 pointer 변수를 인자로 받고,

다른 하나는 reference 변수를 인자로 받습니다.

하지만 하는 일은 동일합니다.

 

 

소스

/*
만든이 : NoSyu
만든 날짜 : 2008-09-12
*/

#include <iostream> // iostream include

// using standard input/ouput
using std::cout;
using std::cin;
using std::endl;

// function declaration
void swap(int *a, int *b); // call-by-reference using pointer swap function
void swap(int &a, int &b); // call-by-reference using reference variable swap function

// main function
int main(void)
{
    int a = 5, b = 6; // swap function 확인 변수

    // 출력
    cout << "a : " << a << ", b : " << b << endl << endl;

    // call-by-reference using pointer swap function
    swap(&a, &b);
    // 출력
    cout << "a : " << a << ", b : " << b << endl << endl;

    // call-by-reference using reference variable swap function
    swap(a, b);
    // 출력
    cout << "a : " << a << ", b : " << b << endl << endl;
    return 0; // 종료~
}

// call-by-reference using pointer swap function
void swap(int *a, int *b)
{
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;

    cout << "call call-by-reference using pointer swap function" << endl;
}

// call-by-reference using reference variable swap function
void swap(int &a, int &b)
{
    int temp;

    temp = a;
    a = b;
    b = temp;

    cout << "call call-by-reference using reference variable swap function" << endl;
}

크리에이티브 커먼즈 라이선스
Creative Commons License

글에 잘못된 점, 다른 점, 부족한 점이 있다면 지적해주세요.
댓글, 트랙백, 메일 모두 고맙습니다.

트랙백 주소 :: http://nosyu.pe.kr/trackback/1687

댓글을 달아 주세요

[로그인][오픈아이디란?]