感谢您查看我的帖子,希望它会相对简单。
我正在尝试更多地了解 QP/C 或 QP/nano,但作为理解它如何工作的一部分,我需要了解 C 语言中的 OOP 概念。详见:
https://www.state-machine.com/doc/AN_OOP_in_C.pdf
我已经完成了 OOP 文档的封装部分,现在正在努力理解继承。在文档中,他们展示了从继承类向上转换为超类的两种方法:
Shape_moveBy((Shape *)&r1, -2, 3);
然后
Shape_moveBy(&r2->super, 2, -1);
但是我无法让这段代码工作?
为了理解这个概念,我尝试制作一些示例代码:
/****************** Inheritance Example ***********************/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* Shape Class */
typedef struct
{
int16_t x; /* x-coordinate of shape's position */
int16_t y; /* y-coordinate of shape's position */
} Shape;
void Shape_ctor(Shape * const me, int16_t x, int16_t y);
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
void Shape_ctor(Shape * const me, int16_t, int16_t y)
{
me->x = x;
me->y = y;
}
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
{
me->x += dx;
me->y += dy;
}
/* End Shape Class */
/* Rectangle Class (Inherited Class below Shape) */
typedef struct
{
Shape super; // inherits shape attributes
uint16_t width;
uint16_t height;
} Rectangle;
void Rectangle_ctor(Rectangle * const me, int16_t x, intt16_t y,
uint16_t width, uint16_t height);
Void Rectangle_ctor(Rectangle * const me, int16_t x, intt16_t y,
uint16_t width, uint16_t height)
{
Shape_ctor(&me->super, x, y);
me->width = width;
me->height = height;
}
/* End Rectangle Class */
int main()
{
Rectangle r1, r2;
// construct rectangles
Rectangle_ctor(&r1, 0, 2, 10, 15);
Rectangle_ctor(&r2, -1, 3, 5, 8);
// operate on the shape
Shape_moveBy((Shape *)&r1, 2, 3);
Shape_moveBy(&r2->super, 2,-1);
return 0;
}
当我编译时出现错误
oop_inher.c In function 'main'
oop_inher.c:77:17: error: invalid type argument '->' (have 'Rectangle {aska struct <anonymous>}')
Shape_moveBy(&r2->super, 2,-1);
我猜我在这里没有正确使用指针,但由于我正在尝试向上投射,我很难跟踪我做错了什么。
如果替换
Shape_moveBy(&r2->超级,2,-1(;
由
Shape_moveBy(&r2.super, 2,-1(;