printf("ho_tari\n");

Shape (dynamic_cast) 본문

C++

Shape (dynamic_cast)

호타리 2023. 9. 8. 17:00

<main.cpp>

#include <iostream>

#include "shape.h"

#include "rectangle.h"

#include "circle.h"

#include <typeinfo>



void printArea(const Shape *ps)

{

	std::cout << "area : " << ps->area() << std::endl;

}



void printShape(const Shape *ps)

{

	if (typeid(*ps) == typeid(Rectangle))          // RTTI : Run Time Type Identification

	{

		std::cout << "rectangle area : " << ps->area() << '\t';

		const Rectangle *p = dynamic_cast<const Rectangle *>(ps);

		std::cout << "diagonal : " << p->getDiagonal() << std::endl;

	}

	else if (typeid(*ps) == typeid(Circle))

	{

		std::cout << "circle area : " << ps->area() << '\t';

		const Circle *p = dynamic_cast<const Circle *>(ps);

		std::cout << "circumference : " << p->getCircumference() << std::endl;

	}

}



int main()

{

	//Shape s(100, 100);

	Shape *ps;



	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;

}

 

<compile 결과>

'C++' 카테고리의 다른 글

Complex6 (inline 함수)  (0) 2023.09.11
String4 (const_cast)  (0) 2023.09.08
Pointer3 (reinterpret_cast)  (0) 2023.09.08
GenderRatio (static_cast)  (0) 2023.09.08
SafeArray4 (try, throw, catch)  (0) 2023.09.08