image.png
    PPT:
    image.png
    image.png
    image.png

    image.png

    image.png
    image.png
    image.png
    image.png
    image.png

    Code1 多态实现:

    1. #include <iostream>
    2. #include <string>
    3. //能解决问题,但维护性不好
    4. using namespace std;
    5. class Base//基类
    6. {
    7. public:
    8. virtual string type()
    9. {
    10. return "Base";
    11. }
    12. };
    13. class Derived: public Base//派生类
    14. {
    15. public:
    16. string type()
    17. {
    18. return "Derived";
    19. }
    20. void printf()
    21. {
    22. cout << "I'm a Derived." << endl;
    23. }
    24. };
    25. class Child : public Base
    26. {
    27. public:
    28. string type()
    29. {
    30. return "Child";
    31. }
    32. };
    33. void test(Base* b)
    34. {
    35. if(b->type()== "Derived")
    36. {
    37. Derived* d = static_cast<Derived*>(b);//危险的转换
    38. d->printf();
    39. }
    40. }
    41. int main()
    42. {
    43. Base b;
    44. Derived d;
    45. Child c;
    46. test(&b);
    47. test(&d);
    48. test(&c);
    49. return 0;
    50. }

    Code2 typeid:

    1. #include <iostream>
    2. #include <string>
    3. #include <typeinfo>
    4. //能解决问题,但维护性不好
    5. using namespace std;
    6. class Base//基类
    7. {
    8. public:
    9. virtual ~Base()
    10. {
    11. }
    12. };
    13. class Derived: public Base//派生类
    14. {
    15. public:
    16. void printf()
    17. {
    18. cout << "I'm a Derived." << endl;
    19. }
    20. };
    21. void test(Base* b)
    22. {
    23. const type_info& tb = typeid(*b);
    24. cout << tb.name()<< endl;
    25. }
    26. int main()
    27. {
    28. int i = 0;
    29. const type_info& tiv = typeid(i);
    30. const type_info& tii = typeid(int);
    31. cout << (tiv == tii) << endl;
    32. Base b;
    33. Derived d;
    34. test(&b);
    35. test(&d);
    36. return 0;
    37. }