rtti2.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // rtti2.cpp -- using dynamic_cast, typeid, and type_info
  2. #include <iostream>
  3. #include <cstdlib>
  4. #include <ctime>
  5. #include <typeinfo>
  6. using namespace std;
  7. class Grand
  8. {
  9. private:
  10. int hold;
  11. public:
  12. Grand(int h = 0) : hold(h) {}
  13. virtual void Speak() const { cout << "I am a grand class!\n";}
  14. virtual int Value() const { return hold; }
  15. };
  16. class Superb : public Grand
  17. {
  18. public:
  19. Superb(int h = 0) : Grand(h) {}
  20. void Speak() const {cout << "I am a superb class!!\n"; }
  21. virtual void Say() const
  22. { cout << "I hold the superb value of " << Value() << "!\n";}
  23. };
  24. class Magnificent : public Superb
  25. {
  26. private:
  27. char ch;
  28. public:
  29. Magnificent(int h = 0, char cv = 'A') : Superb(h), ch(cv) {}
  30. void Speak() const {cout << "I am a magnificent class!!!\n";}
  31. void Say() const {cout << "I hold the character " << ch <<
  32. " and the integer " << Value() << "!\n"; }
  33. };
  34. Grand * GetOne();
  35. int main()
  36. {
  37. srand(time(0));
  38. Grand * pg;
  39. Superb * ps;
  40. for (int i = 0; i < 5; i++)
  41. {
  42. pg = GetOne();
  43. cout << "Now processing type " << typeid(*pg).name() << ".\n";
  44. pg->Speak();
  45. if( ps = dynamic_cast<Superb *>(pg))
  46. ps->Say();
  47. if (typeid(Magnificent) == typeid(*pg))
  48. cout << "Yes, you're really magnificent.\n";
  49. }
  50. // std::cin.get();
  51. return 0;
  52. }
  53. Grand * GetOne()
  54. {
  55. Grand * p;
  56. switch( rand() % 3)
  57. {
  58. case 0: p = new Grand(rand() % 100);
  59. break;
  60. case 1: p = new Superb(rand() % 100);
  61. break;
  62. case 2: p = new Magnificent(rand() % 100, 'A' + rand() % 26);
  63. break;
  64. }
  65. return p;
  66. }