# Include <stdio. h> typedef struct {void (* draw) (void *); // void (* rotate) (void *);} vtable; typedef struct {vtable * vptr; // virtual table pointer} shape; typedef struct {vtable * vptr; int X, Y, W, H;} rect; typedef struct {vtable * vptr; int x, y, r;} cycle; void drawrect (void * P) {rect * Me = (rect *) P ;//............ printf ("drawrect \ n");} void rotaterect (void * P) {rect * Me = (rect *) P; //............ printf ("rotaterect \ n");} void drawcycle (void * P) {cycle * Me = (cycle *) P; //............ printf ("drawcycle \ n");} void rotatecycle (void * P) {cycle * Me = (cycle *) P; //............ printf ("rotatecycle \ n");} vtable rectopers ={& drawrect, & rotaterect}; // virtual function table definition vtable cycleopers ={& drawcycle, & rotatecycle }; int main () {rect rt1 = {& rectopers, 0, 0, 10, 10}; // Implementation of the entity class cycle cy1 = {& cycleopers, 10, 10, 20}; shape * Sh = (shape *) & rt1; SH-> vptr-> draw (SH); SH-> vptr-> rotate (SH ); SH = (shape *) & cy1; SH-> vptr-> draw (SH); SH-> vptr-> rotate (SH); Return 0 ;}
Vtable implements a virtual function table. Each of the three struct sets a vtable as the first position, and the shape class is used as the base class. There is only one vtable * vptr.
After forced type conversion, take the first pointer of each subclass, that is, the pointer referred to by vtable.
Vtable rectopers ={& drawrect, & rotaterect}; // virtual function table definition
Vtable cycleopers ={& drawcycle, & rotatecycle };'
The pointer value has been initialized. Therefore, when calling sharp, it is essentially a pointer that has been assigned a value. Implements the functions of virtual functions.