Ore*_*reo 1 c virtual function
我有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);
}
Run Code Online (Sandbox Code Playgroud)
如果它是一个函数指针,则不是必需的。有或没有,都是一样的。
这个想法是它是“函数的指针”,因此您要取消引用指针才能将其用作函数。但是函数名称实际上实际上也只是指针,并且您也不需要取消引用它们,因此它们是等效的。
(*me->vptr->area)(me)相当于(me->vptr->area)(me)为是printf("foo")等同于(*printf)("foo")(但你永远不会写这种方式)。
您可以保留它或将其删除,这并不重要。就个人而言,如果它专门是一个指向函数的指针,而不是一个命名函数本身,那么我将保留它,以保留“取消使用它”的想法。