일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- null
- SVN
- dataframe
- pi
- mysql
- FIND
- expect
- python
- c++11
- ubuntu
- C++
- boost
- 배열
- SSH
- List
- awk
- if
- sqlite
- pandas
- autovacuum
- sql
- 쉘
- postgresql
- DROP
- conda
- with
- Shader
- Unity
- ngui
- Eclipse
- Today
- Total
その先にあるもの…
[C++] dynamic_cast 본문
사용
기본 클래스에서 파생 클래스로의 다운캐스팅
다중 상속에서 기본 클래스간에 캐스팅
제약
상속관계에서 사용
가상 함수가 1개 이상 꼭 필요
RTTI( runtime type information)이 활성
#include "stdafx.h"
#include <iostream>
using namespace std;
class C0
{
public:
int i = 0;
virtual void print() { cout << "C0 class" << endl; }
};
class C1
{
public:
int i = 0;
virtual void print() { cout << "C1 class" << endl; }
};
class D0 : public C0
{
public:
float f = 1.0f;
void print() { cout << "D0 class" << endl; }
};
class D1 : public C0, public C1
{
public:
void print() { cout << "D1 class" << endl; }
};
void main()
{
C0* pBase = new C0;
C0* pChild1 = new D0;
D0* pChild2 = new D0;
D0* pChild = nullptr;
//error C0*에서 D0*로 변환할 수 없다.
//pChild = pBase;
//컴파일오류가 발생하지 않고 pChild는 nullptr이 된다.
pChild = dynamic_cast<D0*>(pBase);
if (pChild == nullptr)
cout << "failed to casting" << endl;
//error C0*에서 D0*로 변환할 수 없다.
//pChild = pChild1;
pChild = dynamic_cast<D0*>(pChild1);
if (pChild)
pChild->print(); //D0 class
C0* pBase1 = NULL;
C1* pBase2 = new D1;
pBase1 = dynamic_cast<C0*>(pBase2);
if (pBase1)
pBase1->print(); //D1 class
}
'프로그래밍' 카테고리의 다른 글
정규표현식 (0) | 2022.11.18 |
---|---|
정규표현식 정리 (0) | 2019.09.18 |
[C++]const_cast (0) | 2018.12.12 |
[C++]LNK2019 (0) | 2018.10.19 |
[SHELL SCRIPT] 쉘스크립트IF (0) | 2018.03.29 |