[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
I remember when we were in the first class of C ++, the teacher told us that C ++ is an object-oriented language. C ++ has three most important features: inheritance, encapsulation, and polymorphism. Later, with the increase in coding and the accumulation of work experience, I gradually understood the meaning of object-oriented. However, after my work, I will use more programming languages than the C language. At this time, I want to turn the C language into an object-oriented language? Later, through thinking and practice, I found that the C language can also be object-oriented and can also be applied to design patterns. The key lies in how to implement the three important attributes of object-oriented language.
(1) Inheritance
typedef struct _parent{ int data_parent;}Parent;typedef struct _Child{ struct _parent parent; int data_child;}Child;
When designing C language inheritance, we need to place the basic data at the beginning of the inherited structure. In this way, data access, strong data conversion, and data access will not be any problem.
(2) Encapsulation
struct _Data;typedef void (*process)(struct _Data* pData);typedef struct _Data{ int value; process pProcess; }Data;
Encapsulation means that functions and data are tied together, and data are tied together. In this way, we can access all the data through a simple structure pointer and traverse all the functions. Encapsulation, which is a property of a class and of course a property of a data structure.
(3) polymorphism
typedef struct _Play{ void* pData; void (*start_play)(struct _Play* pPlay);}Play;
Polymorphism means that the same interface code is used to process different data. For example, the play structure here is a general data structure. We do not know what pdata is and what processing function start_play is? However, you only need to call pplay-> start_play (pplay) during processing. We don't need to worry about the remaining things, because different interfaces have different functions for processing. We only need to learn to call them.