【发布时间】:2019-05-21 20:43:39
【问题描述】:
我有 C 中的代码示例,它模拟了虚函数 Shape_area()。
有一行代码看不懂:return (*me->vptr->area)(me);
为什么我们在“我”之前使用“*”?
请您向我解释一下那部分好吗? 谢谢
/*shape.h*/
struct ShapeVtbl; /* forward declaration */
typedef struct {
struct ShapeVtbl const *vptr; /* <== Shape's Virtual Pointer */
int16_t x; /* x-coordinate of Shape's position */
int16_t y; /* y-coordinate of Shape's position */
} Shape;
/* Shape's virtual table */
struct ShapeVtbl {
uint32_t (*area)(Shape const * const me);
};
/* Shape's operations (Shape's interface)... */
void Shape_ctor(Shape * const me, int16_t x, int16_t y);
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
uint32_t Shape_area(Shape const * const me) {
return (*me->vptr->area)(me);
}
【问题讨论】:
-
并非您在互联网上看到的每个代码都是好的
-
@P__J__ 这是通过函数指针调用函数的传统方式。后来,显式取消引用成为可选的,但许多人更喜欢保留它,因为它更清晰且与声明符更一致。这样做当然没有错。