首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >面向对象C:构建vtable

面向对象C:构建vtable
EN

Stack Overflow用户
提问于 2016-04-14 00:03:54
回答 1查看 2.1K关注 0票数 0

我正在尝试向自己传授面向对象C的基本知识。我试图构建vtable,然后使用这些来模拟结构的“继承”(尝试在C++中复制类继承)。

我有个问题。我相信这是可能的,但我不知道怎么做。“派生”结构的变量可以从“基本”结构指针中修改吗?

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

//should represent Base
typedef struct Animal
{
    int age;
    void *vtable;
} Animal;

//Cat and dog will inherit Animal. They both have same 'age' variable, and different other parameters
typedef struct Dog
{
    int age;
    double weight;
    void *vtable;
} Dog;

typedef struct Cat
{
    int age;
    int numberOfLives;
    void *vtable;
} Cat;

//some test functions
void Speak_Dog(Animal* a)
{
    printf("Woof!\n");
}

void Speak_Cat(Animal* a)
{
    printf("Meow!\n");
}

//this is where I'm stuck, I would like to keep sending pointer to Animal
double Dog_GetCost(Animal *a)
{
    return 0;//should return age*weight
}

double Cat_GetCost(Animal *a)
{
    return 0;  //should return age*num_lives
}

//build tables
void* Dog_Vtable[2] = {Speak_Dog, Dog_GetCost};
void* Cat_Vtable[2] = {Speak_Cat, Cat_GetCost};

void Construct_Dog(Dog* d)
{
    d->age = 0;
    d->weight = 0;
    d->vtable = Dog_Vtable;
}

void Construct_Cat(Cat* c)
{
    c->age = 0;
    c->numberOfLives = 0;
    c->vtable = Cat_Vtable;
}

int main()
{
    int choice;
    Dog d;
    Cat c;
    Animal* a;

    ((void (*)(Animal*))Dog_Vtable[0])((Animal*)&d);  //print out "woof" - good
    ((void (*)(Animal*))Cat_Vtable[0])((Animal*)&c);  //print out "meow" - good

    printf("Do you want to make dog or a cat? (0/1) ");
    scanf("%d", &choice);

    if(choice == 0)
    {
        a = &d;  //animal is Dog
        a = (Animal*)malloc(sizeof(Dog));  //allocate memory for Dog
        Construct_Dog(a);  //construct it
    }
    else
    {
        a = &c;  //similar for cat
        a = (Animal*)malloc(sizeof(Cat));
        Construct_Cat(a);
    }

    free(a);

    return 0;
}

现在,假设我试图修改第二个int变量(权重或NumLives,视情况而定),我将如何使用*a更改它?我正试着向Object oriented programming with ANSI-C学习,但我没有弄明白这一点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-14 00:10:16

您可以使用((Dog *)a) -> weight = 42.0;((Cat *)a) -> numberOfLives = 9;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36611591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档