const float pi = 3.14;
typedef float (*area)(void*);
typedef struct Shape
{
area p;
}Shape;
typedef struct Circle
{
Shape shape;
float radius;
}Circle;
typedef struct Square
{
Shape shape;
float length;
}Square;
float square_area(void* cp) {
if (cp == NULL) return 0;
printf("square class area \n");
Square* sq = (Square*)cp;
float area = sq->length * sq->length; return area;
}
float circle_area(void* cp) {
if (cp == NULL) return 0;
printf("ciecle class area \n");
Circle* sq = (Circle*)cp;
float area = sq->radius * sq->radius*pi; return area;
}
int main()
{
Square s;
s.length = 10;
Circle c;
c.radius = 10;
s.shape.p = square_area;
c.shape.p = circle_area;
Shape* shape = NULL;
shape = (Shape*)&s;
cout << "Square area:" << shape->p(&s)<<endl;
shape = (Shape*)&c;
cout << "Circle area:" << shape->p(&c)<<endl;
return 0;
}
当Square中两个成员调换时,编译能通过,但是执行时却发生错误
typedef struct Square
{
float length;
Shape shape;
}Square;
然后我又把Shape中添加了一个float,目的是为了和用shape类型偏移时能够和Square对应起来,当Square类型空间给shape指针时能够正确的偏移到计算函数,但是如果Square中还是shape类型的话,又会出错,因为shape类型已经让我改了 shape指针以为已经偏移到了它的函数指针p这里,但是这是Square的空间啊!,偏移到了float,所以出错,此时将Square第二个成员改为和shape一致就行了 虽然这样有点不符合继承的概念了…
|