Main.cpp
//If the file name is a description ending in. cpp This is a C + + source program,//In the source program of C + +, the function of class is identical to the function of struct.Except that their default member properties are not the same (class is private by default,//struct Default is common), the same struct has the this pointer, the same struct//can inherit, same struct also supports all properties of C + + polymorphic, same struct//There is a virtual table, here is a virtual table example of a struct that I do. //Remember in the source file at the end of. CPP, the struct is basically consistent with class. #include <stdlib.h>#include <stdio.h>structa{Virtual voidFun () =0;};structD | Publica{voidFun () {printf("B::fun () \ n"); }};typedef void(*PF) ();voidPrintf (void*arg) {PF F = pf (* (int*) arg); f ();}voidTest () {b b; Printf ((int*)*(int*) &b);}intMain () {test ();return 0;}
Main.c
#include <stdlib.h>#include <stdio.h>//Because structs in a pure C language are not the same as properties in C + +. //First in the pure C language of the struct is not supported polymorphic, can not be constructed,//No This, can not have function, if we want to use pure C struct body to//simulation of a class will be very difficult, the following is my rough wording. structA;typedefvoid(*PF) (structA This);//array of function pointers. structVptrnode;typedefvoid(*PV) (structVptrnode * This);structvptrnode{PV PF;//simulate virtual tables. };voidvtrprintf (structVptrnode * This) {printf ("vtrprintf () \ n");}structa{PF F;//Because the internal structure of a pure C language is not defined as a function, it is replaced with a function pointer. intAstructVptrnode *vptr;structB {PF p;structA *b;//impersonation inheritance, which causes struct B to call the function in base class A. }b;};voidFUN1 (structA This)simulation of the//this pointer. { This->a = -; printf"Fun1 (): a==%d\n", This->A);}intMain () {structA; A.F = (PF) fun1;//Simulate this. A.F (&a);//////////////////A.B.P = (PF) fun1;the//pattern subclass function P overrides the function f in the base class. A.B.P (&a); a.b.b = (structA *) malloc (sizeof(structA));//You must open space here, if you do not open space, you assign a pointer pointer to a definite //The function address will appear with a segment error. A.b.b->f = (PF) fun1; A.b.b->f (&a);the//impersonation subclass invokes the function F of the Father class. //////////////////// //Because the virtual table exists only in the parent class. A.vptr = (structVptrnode *) malloc (sizeof(structVptrnode)); A.VPTR->PF = (PV) vtrprintf;structVptrnode vptr; A.VPTR->PF (&VPTR);return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The understanding of pure C structure and C + + structural body