How to use C to write object-oriented programs

Source: Internet
Author: User
Tags call back signal handler
How to write beautiful C code: Object-oriented C

0 recommended

Http://www.bbs.topsage.com/thread-426058-1-1.html

The object-oriented language is closer to the human way of thinking, which greatly reduces the complexity of the code and improves the readability and maintainability of the Code, traditional C code can also design beautiful code that is easier to read, easier to maintain, and less complex. This article will illustrate this through a practical example.

Basic knowledge

Struct

In addition to providing basic data types, the C language also provides users with the ability to customize data types, that is, struct. In the C language, you can use struct to represent any entity. Struct is the prototype of classes in object-oriented languages. For example:

  1. Typedef struct {
  2. Float X;
  3. Float y;
  4. } Point;

Copy code

Defines a point in a plane coordinate system. A point has two fields, X coordinate and Y coordinate.

The fields in the struct are called struct members. The data type in the struct can be a simple data type or another struct, and even the struct itself can be nested. For example, a standard linked list structure can be defined as follows:

  1. Typedef struct node {
  2. Void * data; // Data Pointer
  3. Int datalength; // Data Length
  4. Struct node * Next; // point to the next node
  5. } Node;

Copy code

We can see that the next pointer type in the struct node is also the node type.

Function pointer

Pointers are the soul of the C language. They are more flexible and powerful than other languages. Therefore, to learn the C language, you must have a good grasp of the pointer. The function pointer refers to the pointer to the first address of the function in the memory ing. Through the function pointer, you can pass the function as a parameter to another function and call it when appropriate, to Implement Asynchronous Communication and other functions.

For example, the signal registration function in Unix/Linux is prototype as follows:

  1. Void (* signal (INT signo, void (* func) (INT)

Copy code

When using it, you need to define a signal processing function (signal handler) externally, and then use signal (signo, Handler) to register the processing program on the process. When the signal occurs, the process can call back the signal processing function.

Use the function pointer as a member of the struct.

As mentioned above, a struct member can be a simple data structure or another struct, or a pointer. When the function pointer is used as a member of the struct, and these functions are only used to manipulate data in the struct, an independent entity can be formed, which contains both data, there are also operations on data, which naturally lead to the concept of class.

Features of object-oriented language

In general, inheritance, encapsulation, and polymorphism are considered to be three features that must be supported by object-oriented languages. It is precisely through these three features that they can reflect the advantages of forward object over process-oriented. Because of the publicity of language developers or other reasons, the object-oriented thinking on the surface needs to be implemented through the language as the carrier. However, in fact, object-oriented is a software design idea, it is completely unrelated to the specific implementation.

Even so, it is undeniable that these so-called pure object-oriented languages are much better than process-oriented languages in terms of code readability and matching with human natural thinking.

Language-level object-oriented

We generally want to describe an object. Generally, we need to describe some attributes of this object. For example, a box is an object with six faces, with colors and weights, whether the attribute is empty or not, and can be put in and retrieved. In an object-oriented language, such an object is usually abstracted into a class ):

  1. Class box {
  2. Clolr color;
  3. Int weight;
  4. Boolean empty;
  5. Put (something );
  6. Something get ();
  7. }

Copy code

You can perform the following operations on the box:

  1. Box. Put (cake );
  2. Box. Get (); // get something from the box.

Copy code

In a process-oriented language, objects are usually transmitted to a global function. In the same case, box is often operated like this:

  1. Put (box, cake); // put a cake in the box
  2. Get (box); // get something from the box

Copy code

Obviously, the first form of code is more common sense. Therefore, most object-oriented languages provide detailed support at the language level, greatly increasing the readability and comprehensibility of the Code. C language, as a flexible and simple language, we can use the simple mechanism provided by C to implement such a beautiful code form.

C language object-oriented

As mentioned above, object-oriented is a software design concept and is language independent. In this section, I will give a list example to illustrate how to design object-oriented code in C language.

Interface Definition

An interface is an important concept in object-oriented language. An interface only promises to external entities what functions the interface can accomplish, but does not expose the implementation method. The advantage is that the implementer can adjust the implementation without touching the code of the interface user.

Let's take a look at the Interface Definition of the linked list:

List 1. Linked List Interface Definition

  1. # Ifndef _ ilist_h
  2. # DEFINE _ ilist_h
  3. // Define the node Structure in the linked list
  4. Typedef struct node {
  5. Void * data;
  6. Struct node * next;
  7. } Node;
  8. // Define the linked list Structure
  9. Typedef struct list {
  10. Struct list * _ this;
  11. Node * head;
  12. Int size;
  13. Void (* Insert) (void * node); // function pointer
  14. Void (* Drop) (void * node );
  15. Void (* clear )();
  16. INT (* getsize )();
  17. Void * (* Get) (INT index );
  18. Void (* print )();
  19. } List;
  20. Void insert (void * node );
  21. Void drop (void * node );
  22. Void clear ();
  23. Int getsize ();
  24. Void * Get (INT index );
  25. Void print ();
  26. # Endif/* _ ilist_h */

Copy code

In the ilist interface, you can clearly see that for a list object (that is, an object), you can perform insert, drop, clear, getsize, get (INDEX) on it) and print operations.

Interface implementation

Listing 2. Constructor

  1. Node * node = NULL;
  2. List * List = NULL;
  3. Void insert (void * node );
  4. Void drop (void * node );
  5. Void clear ();
  6. Int getsize ();
  7. Void print ();
  8. Void * Get (INT index );
  9. List * listconstruction (){
  10. List = (list *) malloc (sizeof (list ));
  11. Node = (node *) malloc (sizeof (node ));
  12. List-> head = node;
  13. List-> insert = insert; // register the insert function on the list object.
  14. List-> drop = drop;
  15. List-> clear = clear;
  16. List-> size = 0;
  17. List-> getsize = getsize;
  18. List-> Get = get;
  19. List-> Print = print;
  20. List-> _ this = List; // use the _ this pointer to save the List itself
  21. Return (list *) List;
  22. }

Copy code

Note that the _ this pointer here can ensure that the external list operations are mapped to the _ this operation to simplify the code.

Listing 3. insert and delete

  1. // Insert a node to a list object
  2. Void insert (void * node ){
  3. Node * Current = (node *) malloc (sizeof (node ));
  4. Current-> DATA = node;
  5. Current-> next = List-> _ this-> head-> next;
  6. List-> _ this-> head-> next = current;
  7. (List-> _ this-> size) ++;
  8. }
  9. // Delete a specified Node
  10. Void drop (void * node ){
  11. Node * t = List-> _ this-> head;
  12. Node * D = NULL;
  13. Int I = 0;
  14. For (I; I <list-> _ this-> size; I ++ ){
  15. D = List-> _ this-> head-> next;
  16. If (D-> DATA = (node *) node)-> data ){
  17. List-> _ this-> head-> next = D-> next;
  18. Free (d );
  19. (List-> _ this-> size )--;
  20. Break;
  21. } Else {
  22. List-> _ this-> head = List-> _ this-> head-> next;
  23. }
  24. }
  25. List-> _ this-> head = T;
  26. }

Copy code

For other implementation code, refer to the download section. If the length is limited, it will not be meaningful.

Test

Test code

All the work we have done above is to ensure that the APIS we expose to users can be as concise and elegant as possible. Now it is time to test:

Listing 4. Test code

  1. Int main (INT argc, char ** argv ){
  2. List * List = (list *) listconstruction (); // construct a new linked list
  3. // Insert some values for testing
  4. List-> insert ("apple ");
  5. List-> insert ("Borland ");
  6. List-> insert ("Cisco ");
  7. List-> insert ("Dell ");
  8. List-> insert ("Electrolux ");
  9. List-> insert ("Firefox ");
  10. List-> insert ("google ");
  11. List-> Print (); // print the entire list
  12. Printf ("list size = % d/N", list-> getsize ());
  13. Node node;
  14. Node. Data = "Electrolux ";
  15. Node. Next = NULL;
  16. List-> drop (& node); // delete a node
  17. Node. Data = "Cisco ";
  18. Node. Next = NULL;
  19. List-> drop (& node); // Delete another node
  20. List-> Print (); // print again
  21. Printf ("list size = % d/N", list-> getsize ());
  22. List-> clear (); // clear the list
  23. Return 0;
  24. }

Copy code

Figure 1. Running result

Conclusion

The UNIX platform developed by C language advocates a design philosophy that allows users to connect these simple tools into powerful and complete applications just like building blocks. It should be said that C has better inherited this point. C language is very concise and powerful. At that time, the object-oriented thinking was not mature due to the early birth of C language, therefore, a large number of procedural C applications have emerged, giving people the illusion that a C language is a process-oriented language. In fact, C only provides some simple, powerful, and universal capabilities, as for what kind of building blocks you want to build, it depends on you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.