UseC LanguageSimulate C ++ encapsulation.
Typedef struct Test
{
Int Info;
Char * pbuff;
INT (* getinfo) (struct test * pthis); // in C ++, each member function will have a this pointer, exceptProgramThe Member is transparent and does not have this pointer in the structure of the C language. Therefore, we do this ourselves;
Void (* inittest) (struct test * pthis); // equivalent to the constructor
Void (* dtor_test) (struct test * pthis); // destructor.
} Testsample;
// Finally implement the inittest () function so that compilation can be completed.
Void getinfo (struct test * pthis)
{
Return pthis-> Info; // and multi-image of C ++ ..
}
Void inittest (struct test * pthis)
{
Pthis-> getinfo = getinfo; // The initialization function must be at the end.
Pthis-> pbuf = (char *) malloc (102 * sizeof (char ));
Pthis-> info = 0;
}
Void dtor_test (struct test * pthis)
{
If (pthis! = NULL)
{
Free (pthis );
}
}
# Include <stdio. h>
Int main ()
{
Testsample test;
Test. inittest (& Test); // This pointer must be passed manually every time ...... trouble.
Test. getinfo (& Test); // This is passed implicitly in the C ++ member function.
Test. dtortest (& Test );//
Return 0;
}