Creative Code

shape(dynamic_cast) 본문

C++ Programming

shape(dynamic_cast)

빛하루 2023. 9. 8. 17:01

※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