C++ 프로그래밍/자료구조와 알고리즘

[자료구조와 알고리즘] C++ : C의 확장

SW Developer 2024. 2. 21. 21:48

C++ : C의 확장

이번 글에서는 앞서 다뤘던 C++ 기초 문법에 대한 내용들을 다시 한번 정리해 볼 것이다.

 

① Pointer vs Reference

② 새로운 메모리 할당

③ Fuction Overloading

④ Default Parameter

⑤ Template

⑥ 기타

 

 

 

① Pointer vs Reference

 

Pointer란?

: 메모리의 주소를 가리키는 변수이다. 32bit 환경에서 4byte의 크기를 가진다.

 

Pointer의 규정요소?

주소(Address)와 유형(Type)으로 이루어져 있으며, 주소만 있는 포인터를 void pointer라고 한다.

 

Pointer 연산

① *  : dereference operator

② & : address of operator

Pointer ± Integer

Pointer - Pointer (덧셈은 성립하지 않음)

 

Pointer 특징

① Low-Level 프로그래밍이 가능하다

② 잘못 사용 시 매우 위험한 코드가 된다

 

 

※ 예시 1

int nValue = 10;
int* pValue = &nValue;//*: int형 포인터를 정의
int nValue2 = *pValue;//*: pValue 포인터가 가리키는 값을 의미

 

주소 변수
100    
104 10 nValue, nValue2
108    
112    
116 104 pValue

 

 

※ 예시 2

int arrayValues[4] = {10,20,30,40};
int* pValue = arrayValues;
int nValue;
nValue = *pValue; //=arrayValue[0]
pValue = pValue + 2; //pValue++;pValue++;
nValue = *pValue; //=arrayValue[2]
int nIndex = pValue - arrayValues; //2, 108-100/4

 

주소 변수
100 10 arrayValues, nValue
104 20  
108 30  
112 40  
116 100 pValue

 

 

Reference란?

Alias임과 동시에 쉬운 Pointer이다. 생성과 동시에 초기화되어야 하며, Pointer를 사용할 때 많이 실수하는 부분들을 보완한 개념이다. 

 

예시

int nValue = 10;
int& rValue = nValue;
rValue = 11; //then nValue = 11, 같은 주소
nValue = 12; //then rValue = 12, 같은 주소

 

 

Pointer vs Reference

 

Pointer 함수 SwapPtr

void SwapPtr(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

 

Reference 함수 SwapRef

void SwapRef(int& x, int& y)
{
    int temp = x;//바로 int형 변수로 초기화 가능
    x = y;
    y = temp;
}

 

SwapPtr vs SwapRef

int first = 0, second = 1;
SwapPtr(&first, &second); //&빼먹으면 crash
SwapRef(first, second);

 

② 새로운 메모리 할당

Type-safe memory allocation: new & delete

: class(struct)의 constructor(생성자)와 destructor(파괴자)를 호출함

 

 

C 방식

struct Person;
Person* pAnyone;
pAnyOne = (Person*)malloc(sizeof(Person));
if(pAnyone == 0) exit(0);
//use pAnyone....
free(pAnyone);

 

 

C++ 방식

struct Person;
Person* pAnyone;
pAnyone = new Person;//새로운 메모리 할당 (생성자)
if(pAnyone == 0) exit(0);
//use pAnyone...
delete pAnyone;//파괴자

 

 

③ Fuction Overloading

같은 이름의 여러 함수들을 정의할 수 있다. 각 함수들을 구분하는 방법은 인자의 타입과 갯수이다.

 

함수 정의

int multiply(int a, int b)
{
    return a*b;
}

double multiply(double a, double b)
{
    return a*b;
}

double multiply(double a, double b, double c)
{
    return a*b*c;
}

 

함수 호출

int nResult;
double dResult;

nResult = multiply(10,20);
dResult = multiply(3.5,2.1);
dResult = multiply(3.5,2.1,1.5);

//int형 + double형 혼합 인자 사용 시
dResult = multiply(10, 2.5); 
//10은 int이므로, int → double (type promotion)

 

④ Default Parameter

함수의 인자를 생략할 수 있다. 생략할 수 있는 인자는 오른쪽 끝에서부터 정의할 수 있다.

 

함수 원형 제공 및 정의

int multiply(int a, int b = 1, int c = 1, int d = 1); //함수의 원형 제공
int multiply(int a, int b, int c, int d)
{
    return a*b*c*d;
}

 

함수 호출

int nResult;

nResult = multiply(5); //multiply(5,1,1,1);
nResult = multiply(5,6); //multiply(5,6,1,1);
nResult = multiply(5,6,7); //multiply(5,6,7,1);

 

 

⑤ Template

파라미터화된 타입으로 함수나 클래스를 정의할 수 있다. Fuction Template, Class Template 등이 있으며, 타입에 관계없이 일반적(generic)인 코드를 제작할 수 있다.

 

※ 예시

 

함수 정의

클래스 T와 같이, 함수를 타입에 관계없이 정의할 수 있다.

template <class T> void SwapGeneric(T& a, T& b)
{
   T temp = a;
   a = b;
   b = temp;
}

 

 

함수 호출

함수 호출 시, 함수의 전달인자를 int형, double형에 관계없이 사용할 수 있다.

int i = 10, j = 20;
SwapGeneric(i,j);//i = 20, j = 10

double di = 1.5, dj = 2.5;
SwapGeneric(di,dj);//di = 2.5, dj = 1.5;

 

 

⑥ 기타

- Inline Fuction을 활용하면 Macro function에 type-safe가 가능하다

- 블럭의 중간에 변수를 정의할 수 있다

- 새로운 표준 입출력 방식인 스트림 모델(cout, cin)을 활용한다

- Operator overloading: 연산자의 의미를 재정의할 수 있다

- Exception Handling: 에러처리를 간명하게 할 수 있다

 

 

 

 

 

 

※ 해당 게시글은 개인 학습의 목적으로, 아래 강의를 수강한 후 정리한 학습노트입니다.

https://inf.run/LNCU