正如 Oli Charlesworth 所指出的,虚拟指针是一个实现细节,所以这个问题在 C++ 方面并没有真正的意义。也就是说,以下虚拟功能(某些功能)的手动实现可能有助于您的理解:
struct vtable {
void (*display)(void*);
void (*setValue)(void*, int);
};
void A_display(void *this_) { /*Cast this_ to A* and do A stuff*/ }
void A_setValue(void *this_, int x) { /*Cast this_ to A* and do A stuff*/ }
vtable A_vtable = {A_display, A_setValue};
struct A {
vtable *vptr = &A_vtable;
int a;
public: A(){}
};
void B_display(void *this_) { /*Cast this_ to B* and do B stuff*/ }
void B_setValue(void *this_, int x) { /*Cast this_ to B* and do B stuff*/ }
vtable B_vtable = {B_display, B_setValue};
struct B {
vtable *vptr = &B_vtable;
int a;
public: B(){}
};
void display(void *obj) {
((*static_cast<vtable**>(obj))->display)(obj);
}
void setValue(void *obj, int) {
((*static_cast<vtable**>(obj))->setValue)(obj, int);
}
当然,这只是提供了虚函数功能的一小部分,但是应该相当简单地看到它vptrs
指向具有固定类型的函数的指针集合。