<C++ study>

[C++]new와 참조자

gosoeungduk 2019. 2. 18. 02:46
반응형

new와 malloc 과 차별화 되는 특징은 바로 new로 메모리 공간을 할당하고 이름을 붙여준 곳을 변수로 간주할 수 있다는 것이다.


그래서 malloc과는 다르게 new 의 변수는 참조자로 참조가 가능하다.


소스로 공부하였다.


#include<iostream>

#include<cstring>

#include<cstdlib>

#include<cstdio>

using namespace std;

typedef struct __Point {

int xpos;

int ypos;

}Point;

Point& PntAdder(const Point &p1, const Point &p2);

int main()

{

Point * ptr1 = new Point;

Point * ptr2 = new Point;

ptr1->xpos = 1;

ptr1->ypos = 2;

ptr2->xpos = 3;

ptr2->ypos = 4;

Point &pntt=PntAdder(*ptr1,*ptr2);

cout << pntt.xpos+pntt.ypos << endl;

}

Point& PntAdder(const Point &p1, const Point &p2)

{

Point * ptt = new Point;

ptt->xpos = p1.xpos + p2.xpos;

ptt->ypos = p1.ypos + p2.ypos;

return *ptt;


PntAdder는 반환 형이 참조자 형태이고 매개변수 또한 참조자 형이다.


위에서 설명한 대로라면 이 PntAdder의 인자는 변수가 들어가야하고 return 형 또한 변수가 return 되어야한다.


위 소스는 이것들이 적용된 결과이다.

반응형