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和HOW? as b_ptr – > function4()给出了编译错误.或者是b_ptr只能访问Derived Vtable中基本类Vtable的大小?
Q2.由于Derived的内存布局必须是(Base,Derived),Base类的Vtable是否也包含在Derived类的内存布局中?
Q3.由于基类Vtable的function1和function2指向基类实现,Derived类的function2指向Base类的function2,在Base类中是否真的需要Vtable? (这可能是我可以提出的最愚蠢的问题,但我仍然对目前的状态存在疑问,答案必须与Q1的答案相关:))
请评论.
谢谢你的耐心等待.
解决方法 作为进一步说明,这是您的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;}总结
以上是内存溢出为你收集整理的c – 继承和多态的低级细节全部内容,希望文章能够帮你解决c – 继承和多态的低级细节所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)