[C++] 如何不用虚函数实现多态

来源:互联网 发布:红宝书软件下载 编辑:程序博客网 时间:2024/06/07 00:05


#include "stdafx.h"typedef void (*fVoid)();class A{public:        static void test()        {                printf("hello A\n");        }        fVoid print;        A()        {                print = A::test;        }};class B : public A{public:        static void test()        {                printf("hello B\n");        }        B()        {                print = B::test;        }};int main(){        A aa;        aa.print();        B b;        A* a = &b;        a->print();        getchar();        return 0;}


这样做的好处主要是绕过了vtable。我们都知道虚函数表有时候会带来一些性能损失。