The object-oriented concept does not seem to be compatible with the C language, but what if you really want to use it? Fortunately, someone has the same idea as you and has made real things. I know more about lw_oopc and ooc.
The full name of ooc is objective oriented c. The author has done a lot of work to implement the three object-oriented features of c language encapsulation, polymorphism, and inheritance, and has also implemented so-called virtual functions. To be honest, I admire ooc's authors and can play C language very well. Ooc's documentation work is also good, but after reading its doc, I still feel a little troublesome to use. So I went to google and finally found lw_oopc.
Lw_oopc only uses two files. The. h and. c files implement three major object-oriented factors, and the implementation process is extremely concise and skillful. To put it bluntly, lw_oopc defines a bunch of macros and calls them.
Let's start with a simple example to see how lw_oopc works as a 'class.
--------------------------------------------
Design an abstract class: Animal with attributes: age and Methods: eat
Inherit Animal and design a class: Dog to implement its Method
Inherit Animal and design a class: Bird. Add method: Fly
The Code is as follows:
***********************************************************<stdio.h>******************************** (*Init)(Animal* (*Eat)(Animal* Animal_Init(Animal*->age = Animal_Eat(Animal********************************* (*Init)(Dog* Dog_Init(Dog*-> Dog_Eat(Animal********************************* (*Init)(Bird* (*Fly)(Bird* Bird_Init(Bird*-> Bird_Fly(Bird* Bird_Eat(Animal*
With these definitions, the usage is the same as that of a simple c ++ class, but the following format should be used to define an instance of a class:
Dog* dog =->Init(dog);
Call your own method:
Bird* bird = ->->Fly(bird);
Calling the inherited method is a little troublesome:
((Animal*)bird)->Eat((Animal*)bird);
Or when the EXTENDS statement does not define the class in the first sentence (the next article will reveal the true faces of each macro), the most secure and cumbersome method is:
SUPER_PTR(bird, Animal)->Eat(SUPER_PTR(bird, Animal));
Is there any meaning? Abstract, inheritance, and polymorphism are all included. We can also see that the use of lw_oopc does not reduce the amount of your code, but increases a lot. But its purpose is not to reduce physical output, but to improve the software structure.
The true face of each macro remains to be revealed in the next article.