- 论坛徽章:
- 24
|
原帖由 zhujiang73 于 2008-5-20 14:43 发表
最简单的继承:
#include
typedef struct
{
int ma;
} A;
typedef struct
{
A parent;
int mb;
} B;
int main (int argc, char *argv[])
{
B b;
B *pb; ...
加上成员函数:
#include <stdio.h>
typedef struct
{
void *p;
int ma;
} A;
typedef struct
{
A parent;
void *p;
int mb;
} B;
typedef struct
{
void (*set_ma)(void *this, int a);
} AC;
typedef struct
{
AC parent;
void (*set_mb)(void *this, int b);
} BC;
void A_set_ma(void *this, int a)
{
((A*)this)->ma = a;
}
void B_set_mb(void *this, int b)
{
((B*)this)->mb = b;
}
void AC_init(AC *pac)
{
pac->set_ma = A_set_ma;
}
void BC_init(BC *pbc)
{
AC_init((AC*)pbc);
pbc->set_mb = B_set_mb;
}
void A_init(A *pa, AC *pac)
{
pa->p = (void*)pac;
}
void B_init(B *pb, BC *pbc)
{
pb->p = (void*)pbc;
}
int main (int argc, char *argv[])
{
BC bc;
B b1, b2;
B *pb1, *pb2;
pb1 = &b1;
pb2 = &b2;
BC_init(&bc);
B_init(pb1, &bc);
B_init(pb2, &bc);
((AC*)(pb1->p))->set_ma((void*)pb1, 10);
((AC*)(pb2->p))->set_ma((void*)pb2, 100);
((BC*)(pb1->p))->set_mb((void*)pb1, 20);
((BC*)(pb2->p))->set_mb((void*)pb2, 200);
printf("b1.ma = %d b1.mb = %d \n", b1.parent.ma, b1.mb);
printf("b2.ma = %d b2.mb = %d \n", b2.parent.ma, b2.mb);
return 0;
}
|
|
|