Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- C++
- 프로그래밍
- 개발
- 코딩테스트
- java정리
- 이웃한 칸
- 사물인터넷
- 개발자
- 자바정리
- java
- 풀스택프레임워크
- SNS
- 코딩독학
- Reflex
- 코딩
- 개인프로젝트
- Project
- 모의 주식
- 백준
- 코테
- 코스닥
- 자바독학
- 주가예측
- frontend
- Python
- 프로그램
- 프로그래머스
- 빅데이터
- backend
- 자바
Archives
- Today
- Total
Creative Code
shape(dynamic_cast) 본문
※main.cpp파일
#include <iostream>
#include "shape.h"
#include "rectangle.h"
#include "circle.h"
#include <typeinfo>
void printArea(Shape *ps) {
std::cout << "area : " << ps->area() << std::endl;
}
void printShape(const Shape *ps) {
if (typeid(*ps) == typeid(Rectangle)) {
std::cout << "rectangle area : " << ps->area() << '\t';
//const Rectangle *p = (const Rectangle *)ps;
const Rectangle *p = dynamic_cast<const Rectangle *>(ps); // 다이나믹 캐스트(부모클래스 타입의 포인터를 자식클래스의 포인터로 바꿀때
std::cout << "diagonal : " <<
p->getDiagonal() << std::endl;
// RTTI : RunTime Type Indentification 실행시간에 부모클래스 타입의 포인터가 가리키는 객체의 타입을 알기 위할 때
} else if (typeid(*ps) == typeid(Circle)) {
std::cout << "circle area : " << ps->area() << '\t';
//const Circle *p = (const Circle *)ps;
const Circle *p = dynamic_cast<const Circle *>(ps);
std::cout << "circumference : " <<
p->getCircumference() << std::endl;
}
}
int main() {
//Shape s(100,100); --> 추상클래스의 객체는 만들수 없다.
Shape *pShapes[5];
pShapes[0] = new Rectangle(10,10,20,5);
pShapes[1] = new Circle(50,50,5);
pShapes[2] = new Rectangle(0,0,100,20);
pShapes[3] = new Rectangle(100,100,100,100);
pShapes[4] = new Circle(100,100,50);
for (int i = 0; i<5; ++i) {
printArea(pShapes[i]);
}
for (int i = 0; i<5; ++i) {
printShape(pShapes[i]);
}
for (int i = 0; i<5; ++i) {
delete pShapes[i];
}
return 0;
}
'C++ Programming' 카테고리의 다른 글
complex6(inline함수, namespace) (1) | 2023.09.11 |
---|---|
string4(const_cast) (0) | 2023.09.08 |
pointer3.cpp(reinterpret_cast) (0) | 2023.09.08 |
genderRatio.cpp(static_cast) (0) | 2023.09.08 |
safeArray4(try-throw-catch) (0) | 2023.09.08 |