1. #include "stdafx.h"
    2. #include <iostream>
    3. using namespace std;
    4. class A {
    5. public:
    6. A() {
    7. a = this;
    8. }
    9. virtual void test()
    10. {
    11. cout << "A::test()\n";
    12. }
    13. ;
    14. static A * a ;
    15. };
    16. A* A::a = nullptr;
    17. class B : A {
    18. public:
    19. void test() {
    20. cout << "调用了test函数\n";
    21. }
    22. };
    23. int main() {
    24. B b;
    25. A::a->test();
    26. return 0;
    27. }

    在类初始化的过程中,父类到子类构造,通过父类的构造函数中的静态成员保存类的指针,从而初始化此指针,指针实际指向值为子类,多态

    结果为
    “调用了test函数\n”