我正在使用 C 进行继承(即使用子类数据类型调用超类的函数),但遇到了别名问题。
在下面,shape
函数是用rectangle
对象调用的。
在 的情况下me->super
,x
和y
是正确的。然而,他们错了(Shape*)me
。
我更喜欢的原因(Shape*)me
是me->super
我想对客户隐藏结构实现。
C标准不应该保证吗?根据第 6.7.2.1.13 节
“……一个指向结构对象的指针,经过适当的转换,指向它的初始成员。结构对象内可能有未命名的填充,但不是在其开头”。
/*shape.h*/
#ifndef SHAPE_H
#define SHAPE_H
typedef struct Shape Shape;
Shape* Shape_ctor(int x, int y);
int Shape_getX(Shape* me);
int Shape_getY(Shape* me);
#endif
/*shape.c*/
#include <stdlib.h>
#include "shape.h"
struct Shape
{
int x;
int y;
};
Shape* Shape_ctor(int x, int y)
{
Shape* me = malloc(sizeof(struct Shape));
me->x = x;
me->y = y;
return me;
}
int Shape_getX(Shape* me)
{
return me->x;
}
int Shape_getY(Shape* me)
{
return me->y;
}
/*rectangle.h*/
#ifndef RECT_H
#define RECT_H
#include "shape.h"
typedef struct Rectangle Rectangle;
Rectangle* Rectangle_ctor(int x, int y, unsigned int width, unsigned int height);
int Rectangle_getWidth(Rectangle* me);
int Rectangle_getHeight(Rectangle* me);
#endif
/*rectangle.c*/
#include <stdlib.h>
#include "rectangle.h"
#include "stdio.h"
struct Rectangle
{
Shape* super;
unsigned int width;
unsigned int height;
};
Rectangle* Rectangle_ctor(int x, int y, unsigned int width, unsigned int height)
{
Rectangle* me = malloc(sizeof(struct Rectangle));
me->super = Shape_ctor(x, y);
me->width = width;
me->height = height;
printf("x: %d\n", Shape_getX(me->super)); //correct value
printf("y: %d\n", Shape_getY(me->super)); //correct value
printf("x: %d\n", Shape_getX((Shape*)me)); // wrong value
printf("y: %d\n", Shape_getY((Shape*)me)); // wrong value
return me;
}
int Rectangle_getWidth(Rectangle* me)
{
return me->width;
}
int Rectangle_getHeight(Rectangle* me)
{
return me->height;
}
/*main.c*/
#include <stdio.h>
#include "rectangle.h"
int main(void) {
Rectangle* r1 = Rectangle_ctor(0, 2, 10, 15);
printf("r1: (x=%d, y=%d, width=%d, height=%d)\n", Shape_getX((Shape*)r1)
, Shape_getY((Shape*)r1)
, Rectangle_getWidth(r1)
, Rectangle_getHeight(r1));
return 0;
}