读书人

用C语言如何实现C++的三个特性(封装

发布时间: 2012-02-28 13:06:35 作者: rapoo

用C语言怎么实现C++的三个特性(封装,继承和多态)?
入题,感谢大家的积极发言~!

[解决办法]
[Ref]

#include <stdio.h>
#include <stdlib.h>

#define VIRTUAL

struct vtable /*虚函数表*/
{
int (*p_geti)(void *); /*虚函数指针*/
void (*p_print)(); /*虚函数指针*/
};

struct shape /*类shape*/
{
void *vptr; /*虚表指针 - 指向vtable*/
int i;
};

struct circle /*类circle*/
{
void *vptr; /*虚表指针 - 指向vtable*/
int i;
};

struct rectangle /*类rectangle*/
{
void *vptr; /*虚表指针 - 指向vtable*/
int i;
};

//------------------------------------
//print() - 虚函数
/*真正调用的函数,在其内部实现调用的多态*/
VIRTUAL void print(void *self) /*参数是对象指针*/
{
const struct vtable * const *cp = self;
(*cp)-> p_print();
}

void shape_print()
{
printf( "this is a shape!\n ");
}

void circle_print()
{
printf( "this is a circle!\n ");
}

void rectangle_print()
{
printf( "this is a rectangle!\n ");
}

//------------------------------------------------------
//geti() - 虚函数
VIRTUAL int geti(void *self)
{
const struct vtable * const *cp = self;
return (*cp)-> p_geti(self); /*这一行出问题*/
}

int shape_geti(struct shape *self) /*具体函数实现时,参数还要是其类型指针*/
{
return self-> i;
}

int circle_geti(struct circle *self) /*具体函数实现时,参数还要是其类型指针*/
{
return self-> i;
}

int rectangle_geti(struct rectangle *self) /*具体函数实现时,参数还要是其类型指针*/
{
return self-> i;
}


int main(int argc, char *argv[])
{
struct shape _shape; /*shape的对象_shape*/
struct circle _circle; /*circle的对象_circle*/
struct rectangle _rectangle; /*rectangle的对象_rect*/

/*声名虚表*/
struct vtable shape_vtable; /*shape对象的vtable*/
struct vtable circle_vtable; /*circle对象的vtable*/
struct vtable rectangle_vtable; /*rectangle的虚表*/

/*给类分配虚表*/
_shape.vptr = &shape_vtable; /*将虚表挂上*/
_circle.vptr = &circle_vtable; /*将虚表挂上*/
_rectangle.vptr = &rectangle_vtable; /*将虚表挂上*/

/*给虚表对应相应的函数*/
shape_vtable.p_print = shape_print; /*赋值相应的函数*/
circle_vtable.p_print = circle_print; /*赋值相应的函数*/
rectangle_vtable.p_print = rectangle_print; /*赋值相应的函数*/

/*给虚表对应相应的函数*/
shape_vtable.p_geti = shape_geti;
circle_vtable.p_geti = circle_geti;
rectangle_vtable.p_geti = rectangle_geti;

/*动态联编实现多态*/
/*因类型的不同而作出不同的反映*/
print(&_shape);
print(&_circle);
print(&_rectangle);

_shape.i = 5;
_circle.i = 19;
_rectangle.i = 1;

/*动态联编实现多态*/
/*因类型的不同而作出不同的反映*/
printf( "_shape 's i is : %d\n ", geti(&_shape));
printf( "_circle 's i is : %d\n ", geti(&_circle));
printf( "_rectangle 's i is : %d\n ", geti(&_rectangle));

system( "PAUSE ");
return 0;
}

读书人网 >C语言

热点推荐