C++不用虚函数实现多态
原文:http://emowuyi.iteye.com/blog/1324159
?
#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。我们都知道虚函数表有时候会带来一些性能损失。