C++ 기본개념을 볼시간이 얼마 안남아서
이제는 중요한 부분만 보고 넘기기로 했다.
다른 클래스나 함수들을 friend로 정의할 수 있다.
클래스 내에서 friend 선언 한 친구들은
클래스에 있는 private 필드들을 사용할 수 있다.
#include <iostream>
class A{
private:
void private_func(){}
int private_num;
// B 클래스는 A의 친구
friend class B;
// func는 A의 친구
friend void func();
};
class B{
public:
void b(){
A a;
// A의 private 함수필드들 이여도, 친구이기 때문에 접근 가능
a.private_func();
a.private_num = 2;
}
};
void func(){
A a;
// A의 private 함수의 필드지만, func는 친구이기 때문에 접근 가능
a.private_func();
a.private_num = 2;
}
C에서는 타입캐스팅 방법이 두가지 있었음
근데 C 스타일식으로 하면 가독성이 너무 떨어진다(?? 아무튼)
C++ 스타일 캐스팅 방법은 4가지를 제공함
(원하는 캐스팅 종류)<바꾸려는 타입>(무엇을 바꿀 것인가?)
static_cast<int>(변수)
(int)(변수)
원하는 행,열 짜리 배열만들기
int** arr; arr = new int*[열]; for(int i = 0; i<열; i++) arr[i] = new int(행);
구조체 관점에서 다시한번 봐보자
struct Address{ int level; // 몇차원 void* next; // 다음 데이터 };
클래스 관점에서 봐보자
`
class Array{
const int dim; // 몇 차원 배열인지
int size; // size[0] size[1] ... size[dim -1] 짜리 배열이다.
struct Address{
int level; // 몇차원
void* next; // 다음 데이터
};
Address * top; // 상단 데이터
public:
Array(int dim, int* array_size):dim(dim){
size = new int[dim];
for(int i = 0; i < dim; i++) size[i] = array_size[i];
}
};
`
재귀함수를 이용해서 N차원 배열을 만들어 보자
재귀함수를 구성하기 전에 이 두가지 스텝만 머리속으로 생각해보면 된다.
- 함수에서 처리하는 것, 즉
현재 단게에서 다음단계로 넘어가는 과정
은 무엇인가?- 재귀 호출이
종료되는 조건
은 무엇인가?
위의 N차원 배열함수 생성 재귀함수의 두가지 스텝은 이렇다
- 재귀조건 : n레벨의 Address 배열의 next에는 다음 레벨인 n+1 레벨의 배열을 지정하면 된다.
- 종료 조건 : Address의 level이 클래스의 dim-1(차원수)인 next에서는 재귀호출이 끝남.
// address 를 초기화 하는 함수. 재귀호출로 구성됨
void initalize_address(Address *current){
if(!current) return;
if(current->level == dim -1){ // 2. 종료조건
current->next = new int[zie[current->level]];
return;
}
current->next = new Address[size[current->level]];
for(int i = 0; i != size[current->level];i++){
// 다음단계로 넘어가는 과정.
(static_cast<Address*>(current->next)+i)->level = current->level + 1;
initalize_address(static_cast<Address *>(current->next)+i);
}
}
근데 코드 보면서 느낀거지만 N차원이 아니라, 2차원 N열짜리 배열을 짜는 느낌인데, 맞나이거
아무튼 이런식으로도 사용가능하구나..