这个问题是我心中的一大疑惑,也很难用语言来形容。有时它看起来很明显,有时却很难破解。所以问题是这样的::
class Base{
public:
int a_number;
Base(){}
virtual void function1() {}
virtual void function2() {}
void function3() {}
};
class Derived:public Base{
public:
Derived():Base() {}
void function1() {cout << "Derived from Base" << endl;
virtual void function4() {cout << "Only in derived" << endl;}
};
int main(){
Derived *der_ptr = new Derived();
Base *b_ptr = der_ptr; // As just address is being passed , b_ptr points to derived object
b_ptr -> function4(); // Will Give Compilation ERROR!!
b_ptr -> function1(); // Calls the Derived class overridden method
return 0;
}
Q1.虽然 b_ptr 指向 Derived 对象,但它访问哪个 VTABLE 以及如何访问?因为 b_ptr -> function4() 给出编译错误。或者 b_ptr 只能访问派生 VTABLE 中基类 VTABLE 的大小?
Q2。既然 Derived 的内存布局一定是 (Base,Derived) ,那么 Base 类的 VTABLE 是否也包含在 Derived 类的内存布局中呢?
Q3。既然基类Vtable的function1和function2指向Base类的实现,而派生类的function2指向Base类的function2,那么基类中真的需要VTABLE吗? (这可能是我能问的最愚蠢的问题,但在我目前的状态下我仍然对此表示怀疑,答案必须与问题1的答案相关:))
请给出意见。
感谢您的耐心等待。
作为进一步的说明,这里是 C++ 程序的 C 版本,显示了 vtable 等。
#include <stdlib.h>
#include <stdio.h>
typedef struct Base Base;
struct Base_vtable_layout{
void (*function1)(Base*);
void (*function2)(Base*);
};
struct Base{
struct Base_vtable_layout* vtable_ptr;
int a_number;
};
void Base_function1(Base* this){}
void Base_function2(Base* this){}
void Base_function3(Base* this){}
struct Base_vtable_layout Base_vtable = {
&Base_function1,
&Base_function2
};
void Base_Base(Base* this){
this->vtable_ptr = &Base_vtable;
};
Base* new_Base(){
Base *res = (Base*)malloc(sizeof(Base));
Base_Base(res);
return res;
}
typedef struct Derived Derived;
struct Derived_vtable_layout{
struct Base_vtable_layout base;
void (*function4)(Derived*);
};
struct Derived{
struct Base base;
};
void Derived_function1(Base* _this){
Derived *this = (Derived*)_this;
printf("Derived from Base\n");
}
void Derived_function4(Derived* this){
printf("Only in derived\n");
}
struct Derived_vtable_layout Derived_vtable =
{
{ &Derived_function1,
&Base_function2},
&Derived_function4
};
void Derived_Derived(Derived* this)
{
Base_Base((Base*)this);
this->base.vtable_ptr = (struct Base_vtable_layout*)&Derived_vtable;
}
Derived* new_Derived(){
Derived *res = (Derived*)malloc(sizeof(Derived));
Derived_Derived(res);
return res;
}
int main(){
Derived *der_ptr = new_Derived();
Base *b_ptr = &der_ptr->base;
/* b_ptr->vtable_ptr->function4(b_ptr); Will Give Compilation ERROR!! */
b_ptr->vtable_ptr->function1(b_ptr);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)