dwrswr/cpp-module-06-guide
0
1#include "identify.hpp"2#include "A.hpp"3#include "B.hpp"4#include "C.hpp"5#include <cstdlib>6#include <ctime>7#include <exception>8#include <iostream>9 10Base *generate(void)11{12 static bool seeded = false;13 14 if (!seeded)15 {16 std::srand(static_cast<unsigned int>(std::time(NULL)));17 seeded = true;18 }19 switch (std::rand() % 3)20 {21 case 0:22 return (new A());23 case 1:24 return (new B());25 default:26 return (new C());27 }28}29 30void identify(Base *p)31{32 if (dynamic_cast<A *>(p))33 std::cout << "A" << std::endl;34 else if (dynamic_cast<B *>(p))35 std::cout << "B" << std::endl;36 else if (dynamic_cast<C *>(p))37 std::cout << "C" << std::endl;38}39 40void identify(Base &p)41{42 try43 {44 (void)dynamic_cast<A &>(p);45 std::cout << "A" << std::endl;46 return ;47 }48 catch (std::exception &)49 {50 }51 try52 {53 (void)dynamic_cast<B &>(p);54 std::cout << "B" << std::endl;55 return ;56 }57 catch (std::exception &)58 {59 }60 try61 {62 (void)dynamic_cast<C &>(p);63 std::cout << "C" << std::endl;64 }65 catch (std::exception &)66 {67 }68}69 