c – 继承和多态的低级细节

前端之家收集整理的这篇文章主要介绍了c – 继承和多态的低级细节前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个问题是我头脑中隐藏的一大疑问,也难以用言语来描述.有时似乎很明显,有时候很难破解.所以问题就像这样::
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 &lt&lt "Derived from Base" &lt&lt endl; 
     virtual void function4() {cout &lt&lt "Only in derived" &lt&lt 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的内存布局必须是(B​​ase,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;
}
原文链接:https://www.f2er.com/c/116212.html

猜你在找的C&C++相关文章