可以使用函数指针进行优化。编译器可以将虚函数表的指针存储在对象的内存布局中,而不是在虚函数指针中。这样,通过偏移量,编译器可以直接访问虚函数表中的指针,而无需通过虚函数指针进行间接访问。
以下是一个示例代码,展示了如何通过使用函数指针来访问虚函数:
#include
using namespace std;
class Base {
public:
virtual void print() { cout << "Base::print" << endl; }
};
class Derived : public Base {
public:
void print() { cout << "Derived::print" << endl; }
};
typedef void (*Fun)(void);
void call_virtual_function(Base* obj, int offset)
{
// 定义函数指针,通过偏移量访问虚函数表
Fun f = (Fun)*((int*)*(int*)obj + offset);
f();
}
int main()
{
Base* ptr = new Derived;
// 偏移量为0,调用 Derived::print()
call_virtual_function(ptr, 0);
// 偏移量为1,调用 Base::print()
call_virtual_function(ptr, 1);
delete ptr;
return 0;
}
输出结果为:
Derived::print
Base::print