C中的向上转换(学习类继承)

时间:2018-01-04 12:29:38

标签: c oop upcasting

感谢您查看我的帖子,希望它会相对简单。

我正在尝试更多地了解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);

我猜我在这里没有正确使用指针,但是因为我正在尝试向上转换,所以我很难跟踪我做错了什么。

1 个答案:

答案 0 :(得分:0)

如果更换,该怎么办

Shape_moveBy(&r2-> super,2,-1);

通过

Shape_moveBy(&r2.super,2,-1);