/downcast/ch01/main.cpp

https://github.com/jinjianxin/My-Program · C++ · 117 lines · 98 code · 18 blank · 1 comment · 13 complexity · 5fcae3da6a371700af4859671752077b MD5 · raw file

  1. #include <vector>
  2. #include <iostream>
  3. using namespace std;
  4. class Security
  5. {
  6. protected:
  7. enum { BASEID = 0};
  8. public:
  9. virtual ~Security() {};
  10. virtual bool isA(int id) {return (id == BASEID);}
  11. };
  12. class Stock : public Security
  13. {
  14. typedef Security Super;
  15. protected:
  16. enum {OFFECT = 1,TYPEID = BASEID+OFFECT};
  17. public:
  18. bool isA(int id)
  19. {
  20. return id == TYPEID || Super::isA(id);
  21. }
  22. static Stock *dynacast(Security *s)
  23. {
  24. return (s->isA(TYPEID))? static_cast<Stock *>(s):0;
  25. }
  26. };
  27. class Bond : public Security
  28. {
  29. typedef Security Super;
  30. protected:
  31. enum {OFFECT = 2,TYPEID = BASEID+OFFECT};
  32. public:
  33. bool isA(int id)
  34. {
  35. return id == TYPEID || Super::isA(id);
  36. }
  37. static Bond *dynacast(Security *s)
  38. {
  39. return (s->isA(TYPEID))? static_cast<Bond *>(s):0;
  40. }
  41. };
  42. class Investment : public Security
  43. {
  44. typedef Security Super;
  45. protected:
  46. enum {OFFECT = 3,TYPEID = BASEID+OFFECT};
  47. public:
  48. bool isA(int id)
  49. {
  50. return id == TYPEID || Super::isA(id);
  51. }
  52. static Investment *dynacast(Security *s)
  53. {
  54. return (s->isA(TYPEID))? static_cast<Investment *>(s):0;
  55. }
  56. void special()
  57. {
  58. cout<<"special Investment function"<<endl;
  59. }
  60. };
  61. class Metal : public Investment
  62. {
  63. typedef Security Super;
  64. protected:
  65. enum {OFFECT = 4,TYPEID = BASEID+OFFECT};
  66. public:
  67. bool isA(int id)
  68. {
  69. return id == TYPEID || Super::isA(id);
  70. }
  71. static Metal *dynacast(Security *s)
  72. {
  73. return (s->isA(TYPEID))? static_cast<Metal *>(s):0;
  74. }
  75. };
  76. int main(int argc,char *argv[])
  77. {
  78. vector<Security *> portfolio;
  79. portfolio.push_back(new Metal);
  80. portfolio.push_back(new Investment);
  81. portfolio.push_back(new Bond);
  82. portfolio.push_back(new Stock);
  83. for(vector<Security*>::iterator it = portfolio.begin();it !=portfolio.end();++it)
  84. {
  85. // Investment *cm = Investment::dynacast(*it);
  86. Investment *cm = dynamic_cast<Investment *>(*it);
  87. if(cm)
  88. cm->special();
  89. else
  90. cout<<"not an Investment"<<endl;
  91. }
  92. Security *sp = new Metal;
  93. Investment *cp = Investment::dynacast(sp);
  94. if(cp)
  95. cout<<"it's an Investment"<<endl;
  96. Metal *mp = Metal::dynacast(sp);
  97. if(mp)
  98. cout<<"it's a Metal too!"<<endl;
  99. }