참조자와 함수의 호출관계
참조자와 함수의 호출관계가 헷갈려서 나름대로 정리해본다.
#include <iostream> using namespace std; void Swap(int* &a, int* &b) { int temp = a; a = b; b = temp; } int main(void) { int a=10, b=20; int *ptr1=&a; int *ptr2=&b; cout << ptr1 << " [before] " << ptr2 << endl; cout << *ptr1 << " [before] " << *ptr2 << endl; Swap(ptr1, ptr2); //인자 넘겨줄 때 헷갈려 : int* &a는 int 형 포인터 변수의 별명을 선언하는 형태! cout << ptr1 << " [after] " << ptr2 << endl; cout << *ptr1 << " [after] " << *ptr2 << endl; return 0; } /* void Swap(int &a, int &b) { int temp = a; a = b; b = temp; } int main(void) { int a=10, b=20; int *ptr1=&a; int *ptr2=&b; cout << ptr1 << " [before] " << ptr2 << endl; cout << *ptr1 << " [before] " << *ptr2 << endl; Swap(*ptr1, *ptr2); //인자 넘겨줄 때 헷갈려 : int &a는 int 형 변수의 별명을 선언하는 형태! cout << ptr1 << " [after] " << ptr2 << endl; cout << *ptr1 << " [after] " << *ptr2 << endl; return 0; } */ |
#include <iostream> using namespace std; typedef struct xy_point { int xpos; int ypos; }Point; Point& adder(const Point &p1, const Point &p2) //int &p1이라고 생각하면 int 형 변수의 별명을 선언하는 형태! { Point *sum = new Point; sum->xpos = p1.xpos + p2.xpos; sum->ypos = p1.ypos + p2.ypos; return *sum; //위와 같은 맥락으로 Point& *sum } int main(void) { Point *num1 = new Point; Point *num2 = new Point; num1->xpos=10; num1->ypos=20; num2->xpos=20; num2->ypos=100; cout << adder(*num1, *num2).xpos << endl; //그래서 이렇게 넘겨준다. Point 형 변수 값으로! cout << adder(*num1, *num2).ypos << endl; delete num1; delete num2; return 0; } |