Because C language is a process-oriented language, in the process of larger projects, the structure will appear somewhat loose. Management cannot help but be powerless.
In fact, in the process of using C language to write programs, you can also introduce some objects of the image of the idea. Here we will talk about how to express these thoughts in C language:
1. Package
This is the simplest, C language, although there is no class, but there are struct. It's a good thing. We can simulate class behavior by depositing data and function pointers in a struct.
typedef struct _parent{
int A;
int b;
void (*print) (struct _parent *this);
} Parent;
2. Inheritance
It can be a bit difficult to inherit completely in the C language. But if it's simply done, make sure that the subclass contains all the members of the parent class. It's still not difficult.
typedef struct _child{
parent parent;
int c;
} child;
3. Polymorphism
This feature is probably the most useful in object-oriented thinking.
It takes a little bit of skill to implement this feature in C, but it's not impossible.
We use the two structural bodies defined above as parent, child. A simple description of a polymorphic example.
void Print_parent (parent *this) {printf ("a =%d. B =%d.\n", This->a, this->b);
void Print_child (Parent *this) {Child *p = [Child *] this;
printf ("a =%d. B =%d. C =%d.\n", P->parent.a, p->parent.b, p->c);
Parent *create_parent (int a, int b) {parent *this;
this = NULL;
This = (parent *) malloc (sizeof (parent));
if (this!= NULL) {this->a = A;
This->b = b;
This->print = print_parent;
printf ("Create parent successfully!\n");
return to this;
} void Destroy_parent (parent **p) {if (*p!= NULL) {free (*p);
*p = NULL;
printf ("Delete parent successfully!\n");
} *create_child (int a, int b, int c) {child *this;
this = NULL;
this = (Child *) malloc (sizeof);
if (this!= NULL) {this->parent.a = A;
this->parent.b = b;
This->c = C;
This->parent.print = Print_child; printf ("Create child successfully!\n");
return to this;
} void Destroy_child (child **p) {if (*p!= NULL) {free (*p);
*p = NULL;
printf ("Delete child successfully!\n");
int main () {Child *p = Create_child (1, 2, 3);
Parent *q;
/*use parent Pointer to point to child*/q = (parent *) p;
/*be attention!*//*actually The child ' s print function is called!*/q->print (q);
Destroy_child (&P);
return 0; }