The second interview question: C language How to implement classes in C + +
#include <stdio.h>
//C languages do not have classes, but you can use a struct as a class
//Unlike classes, structs can only define variables, cannot define functions, and can implement their functions
//define "classes" by means of function pointers. The member variable and the method
typedef struct person{
char name;
int age;
void (*eatfunction) (struct person this, int num);
} person;
define function
void eatfunction (struct person this, int num) {
printf ("test\n");
}
The constructor for the definition "class"
//is different from the object-oriented, the C language "class" constructor cannot be placed in "class", can only be placed outside of "class"
//constructor primarily completes the initialization of the variable, and the assignment person of the function pointer
* Newperson (person *this) {
this->name = ' A ';
This->age =;
This->eatfunction = eatfunction;
}
The main function calls
int main () {person person
;
Newperson (&person);
Person. Eatfunction (person,0);
return 0;
Note: When testing to save in. c format, the. cpp format runs the error, because this is the keyword in C + +.
Reference Blog: http://dongxicheng.org/cpp/ooc/