본문 바로가기

프로그래밍 언어/C++34

콜백함수 (함수객체, 템플릿) 1. 콜백함수2. 함수포인터를 사용할 경우3. 템플릿 사용 안할 경우4. 템플릿을 사용 할 경우콜백함수원하는 순간에 원하는 함수를 호출한다인자로서 동작을 넘길때 사용 (유용)함수 포인터의 경우 상태를 저장할 수 없으므로, 하드코딩해야한다 함수포인터를 사용할 경우class Item{public:public: int _rarity = 0; int _ItemId = 0; int _ownerId = 0;};bool FindByOwnerId_FUNC(const Item* item){ return (item->_ownerId == 100);}Item* FindItem(Item items[], int itemCount, bool(*selector)(const Item* item)){ for (int i = 0; i .. 2024. 7. 5.
Template (클래스 템플릿 , c++) 1. 클래스 템플릿               2. 클래스 템플릿 특수화    3. 클래스 템플릿 다중 인자 클래스 템플릿templateclass RandomBox{public: T GetRandomData() { int idx = rand() % 10; return _data[idx]; }public: T _data[10];};int main(){ RandomBox rb1;}class 선언 위에 템플릿 선언class 내부에서 아직 미정된 타입인 부분에 템플릿 사용인스턴스 생성시, 처럼 타입 지정 클래스 템플릿 특수화templateclass RandomBox{public: T GetRandomData() { int idx = rand() % 10; return _data[idx]; }publ.. 2024. 7. 5.
Template (함수 템플릿 - c++) 1. 함수 템플릿 형태   2. 함수 템플릿 특징   3. 함수 템플릿 특수화  함수 템플릿 형태//templatetemplatevoid Print(T a){ cout (50.f); //명시적으로도 가능 Print(50.f); Print(50.0); Print("Hello");}템플릿이 사용되는 함수 위에 template 정의template  또는 template다양한 타입을 받을 수 있는 형태template서로다른 A,B,C 타입 3개를 받을 수 있다templatevoid Print(T t, A a, B b){ cout (3.f, 50, 50.f); //명시적으로도 가능 } 함수 템플릿 특징장점코드 재사용성이 높다타입 안정성유연하게 코드 작성 가능단점복잡성 증가가독성 문제컴파일 시간 증가  함수 템플릿.. 2024. 7. 5.
함수 객체 (C++) 1. 함수객체 형태2. 함수객체 특징 함수 객체 형태//class [함수객체이름]class Functor{public: //[반환타입] oprator()([인자],..) { //TODO } void operator()() { cout 클래스와 동일하다연산자 오버로딩을 통해서 클래스가 함수로서 사용할 수 있도록 한다. 함수 객체 특징연산자 오버로딩을 통해 여러종류의 반환타입, 인자타입 및 개수를 생성할 수 있다.상태값을 가질 수 있다 ( ex) _value ) 2024. 7. 5.
함수포인터 (C++) 1. 함수포인터 형태2. 함수포인터 특징3. 함수포인터와 멤버변수 함수 포인터 형태[반환TYPE] (*[함수포인터이름]) ([인자],..)ex)int (*intPtr) (int num1,int num2); typedef int(FUNC_)(int, int);typedef int(*FUNC_PTR)(int, int);int Add(int a, int b){ return a + b;}int main(){ FUNC_* a = Add; cout Typedef 연관일반적인 typedeftypedef int INT; // int를 INT로 사용하겠다 typedef int (FUNC) (int num1, int num2);FUNC : int의 반환타입을 가지고, 인자 num1, num2를 가지는 함수typ.. 2024. 7. 5.
static_cast, dynamic_cast, const_cast, reinterpret_cast 1. static_cast2. dynamic_cast3. const_cast4. reinterpret_cast Static_cast일반적으로 많이 사용되는 캐스팅C스타일 ( (double) num; ) "()" 보다 안전한 타입변환 방법 Static_cast 종류기본 타입 간 변화int i = 10;double b = static_cast i;포인터 간의 변화 (** 주로 많이 사용)class Base{};class Child : public Base{};Base* basePtr = new Child;Child* childPtr = static_cast(basePtr);void 포인터 특정 포인터로 변환void *ptr = &i;int* intPtr = static_cast(ptr);열거형과 정수형 간의.. 2024. 7. 4.