How can Inheritance be modelled using C? [duplicat

2019-01-30 08:09发布

This question already has an answer here:

Is it possible to model inheritance using C? How? Sample code will help.

Edit: I am looking to inherit both data and methods. Containership alone will not help. Substitutability - using any derived class object where a base class object works - is what I need.

8条回答
我只想做你的唯一
2楼-- · 2019-01-30 08:59

It should be possible, at least to some extent.

What exactly do you need to model? The inheritance of the data or the methods?

Edit: Here's a short article that I found: http://fluff.info/blog/arch/00000162.htm

查看更多
Explosion°爆炸
3楼-- · 2019-01-30 08:59
#include <stdio.h> 

///////Class Cobj
typedef struct Cobj{
    int x;
    void (*setptr)(char * s,int val);
    int (*getptr)(char * s);
} Cobj;

void set(char * s,int val)
{
    Cobj * y=(Cobj *)s;
    y->x=val;
}
int get(char * s){
    Cobj * y=(Cobj *)s;
    return y->x;
}
///////Class Cobj
Cobj s={12,set,get};
Cobj x;

void main(void){
    x=s;
    x.setptr((char*)&x,5);
    s.setptr((char*)&s,8);
    printf("%d %d %d",x.getptr((char*)&x),s.getptr((char*)&s) ,sizeof(Cobj));
}
查看更多
登录 后发表回答