我想在C中实现多级继承,其中基类作为指针继承。例如:
typedef struct Shape_s {
int s;
}Shape;
typedef struct Circle_s {
Shape* base;
int c;
}Circle;
typedef struct ColoredCircle_s {
Circle* base;
int cc;
}ColoredCircle;
Run Code Online (Sandbox Code Playgroud)
我想要指针,因为我想让基类成为“私有”,无法访问它。我还想要多态性 - 所有与 Shape 一起使用的函数也必须与派生类一起使用。例如:
shapeDraw(shape);
shapeDraw((Shape*)circle);
shapeDraw((Shape*)coloredCircle);
Run Code Online (Sandbox Code Playgroud)
上面的示例仅适用于一级继承。我不知道如何在更多级别上做到这一点。
您不应该对基本结构使用指针。只需使用结构包含使基本结构成为当前结构的标头。
typedef struct Shape_s {
int s;
}Shape;
typedef struct Circle_s {
Shape base;
int c;
}Circle;
typedef struct ColoredCircle_s {
Circle base;
int cc;
}ColoredCircle;
Run Code Online (Sandbox Code Playgroud)
对于现有的结构定义,您需要按照指针来访问基本结构。
shapeDraw(shape);
shapeDraw(circle->base);
shapeDraw(coloredCircle->base->base);
Run Code Online (Sandbox Code Playgroud)
这样做时无法隐藏级别数。您不能仅通过强制转换来完成此操作,因为这不会取消对指针的引用。