Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the encapsulation in C language object-oriented programming?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what is the encapsulation in C language object-oriented programming". In the daily operation, I believe that many people have doubts about what the encapsulation in C language object-oriented programming is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is encapsulation in C language object-oriented programming". Next, please follow the editor to study!

1. What is the basic concept of object-oriented?

This object is not another object, although sometimes this object can be the object in your head, so let's start with the object we misunderstand. Although I don't have it, I can use my own straight thinking and think that an object can also be dropped. Then I will get into the object of my straight head. I have an object, this object, fair skin and beautiful legs. With the words in the poem is "Hao wrist freezing frost and snow, edge people like the moon", the beautiful Jiangnan woman, who does not like it. Since it is imagination, the object is not only skin and skin and beautiful legs, but also love you, can accompany you when you are lonely, can be by your side when you are sad, and will not be unreasonable when you play games. Such an object is so good, it is simply the lover of the dream, but it is only in the thought (sigh).

Through the above example, the imaginary object, which has the characteristics of the object, is not very consistent with human characteristics and is easy to understand. So let's extract the general features of the object from the example above.

Feature 1: attribut

Let's go back to my imagination of the object, what the object is like, Hao wrist frost and snow, edge people like the moon, this is the attribute of the object, that is, what it looks like. Of course, attributes are not just appearance, you can add more attributes, such as a good voice, age 20, and so on.

Feature 2: behavior

The action that an object has is behavior. The above example is that the object loves you very much, can accompany you when he is sad, can also accompany you when he is lonely, and so on, which is the action of the object and what the object can do.

Objects and classes

We know what the object is, but have you found that this object is very extensive, that is, I do not know that there is one object in my imagination, and there can be more than one object in line with my imagination, that is, I can imagine many more objects. I can imagine that there are "three thousand beautiful goddesses of concubines in the harem". These three are all in line with the characteristics of my object. These characteristics are classes, that is, there is not only one person in line with my imagination, there can be more than one, as long as this person meets the characteristics of my imagination, she is under this category.

What is the relationship between the class and the object? The object is a special case of this class, how to understand it?

In my imagination, there are many attributes that meet the attributes of a beautiful woman, but I don't know who it is, but one day I saw this person in the animation. Her name is Xiao A. Xiao An is an object under the big beauty category. Another day, I met another person, but also in line with my definition of a big beauty, this object, her name is Xiao B. Both Xiao An and Xiao B meet the definition, that is, under this class, and Xiao An and Xiao B are a special case, that is, the people under this class, are unique.

Object-oriented programming

It's a clich é. Let's take a brief look at what process-oriented programming looks like. Imagine a scene that is more exciting. One day brother Jie misses you and plans to go home and play video games with you, so what should he do to invite you to go home and play video games?

Process-oriented solution: simplify in a simpler way

1: first of all, he was dressed in a suit, dressed like a dog, and looked very handsome, and the little sister said she was very handsome.

2: take a taxi to your house

3: invite graciously

What is the object-oriented solution: let's see that he invites you to involve several objects, taxi hailing object, inviting object, playing electric object, going home object. So how does the partner do it? Let's take a look at the execution order: brother Jie first called the dressing object to dress up, and then called the taxi object to go to your house. When I got to your house, I called the behavior of the invitation object and sent out the invitation, and then you called the behavior of the invitation object and rejected brother Jack, who called the behavior of the emotional object, which made me feel very sad.

Dress up object:

Behavior: dressing up

Taxi-hailing target:

Attribute: taxi hailing person

Attribute: taxi location

Behavior: get in the car

Invitation object:

Attribute: inviter

Attribute: invitation result

Behavior 1: accept

Behavior 2: refuse

Behavior 3: send out an invitation

Who to go home to:

Attribute: the way home

Attribute: time to go home

Behavior: go home

Emotion:

Attribute: degree

Behavior 1: sad

Behavior 2: sad

Behavior 3: very sad

From the above example, you can probably see the difference between object-oriented programming and process-oriented programming. The unit of object-oriented programming is the object, and everything done is performed by the object. Objects can be called by many objects, Jackie can call the invitation behavior in the invitation object, or you can call the invitation object to send out the action of rejecting the invitation. What the properties of an object are and how to define them are flexible.

See the above example: object-oriented programming = process-oriented + object-oriented. The object highly encapsulates some behavior, and then the commander, that is, we call it in a certain order (process-oriented) according to our own ideas, in the process, there will be a certain amount of data interaction between objects and behavior calls between certain objects.

Another example: the realization of a tracking car

Construction object: sensor controller trolley

Car object:

Attribute: current offset valu

Behavior: forward, backward, left, right

Controller:

Attribute: input value, output value

Behaviors: calculating control valu

Sensor:

Attribute: sensor measurement sensor quantity sensor

Behaviors: measuring

/ pseudo code void Follow_mark (void) {call the sensor object to measure, save the measured value to the device measured value, call the controller object, take the measured value of the sensor as the input parameter, save the calculated result and call the trolley object, and calculate the current offset according to the control value passed in by the control. Then the left / right turn behavior is called according to the offset. Second, C language realizes the three major features of object-oriented and object-oriented.

Understand the idea of object-oriented, the idea is the most important, the feature is secondary. Object-oriented has three major characteristics, we can more or less achieve, java,python,C++ all have, but C can also be achieved, but it will be more troublesome, the three major features are encapsulation, inheritance, polymorphism. These three features can help achieve object-oriented programming and make object-oriented more elegant. Let's first understand the encapsulation of three of the three features.

A brief introduction to object-oriented encapsulation

Encapsulation is to encapsulate the characteristics of an object so that the properties and behavior of the object can only be accessed through the object. In the above example, the properties and behavior of the invited object are encapsulated, and we can only call the invited object to invoke the behavior of the invited object.

Advantages:

1. Hide the internal details, like a function. You only need to call the behavior of the invitation object to issue the invitation without knowing the underlying implementation.

2. Safer and better reusability. The values of objects are encapsulated and hidden. Generally, programmers will only provide corresponding interfaces to access them and cannot modify them directly. Reusability, from the above example, anyone can invoke the behavior of the object.

Code implementation-basic version

The basic version does not involve function pointers and function tables. Learn this basic version and understand the implementation of the simplest object-oriented encapsulation.

Before implementation, let's think about what structure C has to implement encapsulation attributes, various attributes. This is very simple, the structure, can put all kinds of properties.

How to reflect the behavior? you can realize all kinds of behaviors and functions. The following polymorphism will involve function pointers, which can be achieved by using function pointers, which are all later, which will be introduced in a later article.

Then let's do a PID controller object, if you don't understand, it doesn't matter, this is just a controller, there are input, output, debugging parameters, understand these on the line. The specific implementation process, the internal details do not understand it does not matter, this is not important, my code will mark it.

Then we read the code directly and enter the difficult mode: the code will have more detailed comments, which is easy to understand!

/ / start to construct the object, since it is a controller, the object must have input, output, debug parameter / / attribute is: parameter value, input value, output value / / behavior is: set parameter, view parameter, calculate output based on input, construct object, delete object / / attribute: implement # include "stdio.h" # include # include / / controller object attribute typedef struct {int input with structure / * controller input * / int ouput;/* controller output * / int packs parameterdirection I controller parameters * control debug parameters * / int Sum_error;/* total deviation, positional PID integral related parameters * / int Last_error;/* last deviation, positional PID integral related parameters * /} controller;// construct object, initialize controller * Ctor_controller (void) {controller * temp Temp= (controller *) malloc (sizeof (controller)); / / Zero memset (temp,0,sizeof (controller)); return temp;} / Delete object void Del_ontroller (controller * const Me) {if (Meteorological null) free (Me);} / / set controller parameter void Write_controller (controller * const Me,int P } / / read the value of the controller parameter controller Read_controller (const controller * const Me,int P _ int I ~ int D) {return (* Me) } / / calculate the controller output. It doesn't matter if you don't understand the details. You only need to know that the input deviation is deviation, and you will output a calculation result. This result can help control / / as to how the deviation defines when the PID controller is needed, you will know int Out_controller (controller * const Me,int input) {float iIncpid=0; int now_error=input;// current deviation Me- > Sum_error+=input. / / Product component limiting, mode integration over-saturation if (Me- > Sum_error > 500) {Me- > Sum_error = 500;} if (Me- > Sum_error)

< -500) { Me->

Sum_error =-500;} Me- > ouput=Me- > P_parameter * input / / P + Me- > I_parameter * Me- > Sum_error / / I + Me- > D_parameter * (now_error-Me- > Last_error); / / D Me- > Last_error=now_error / / Storage error, used to calculate return (Me- > ouput) next time; / / return the calculated value} int main () {controller * test; controller read_val; / / construct, create an object test=Ctor_controller (); / / set the value of the object Write_controller (test,1,1,1) / / View the value of the object read_val=Read_controller (test,1,1,1); printf ("object P =% d ID% d dating% d\ r\ n", read_val.P_parameter,read_val.I_parameter,read_val.D_parameter); / / call the controller once: printf ("controller output =% d\ r\ n", Out_controller (test,100) / / Delete / destroy an object Del_ontroller (test);}

Output result:

Object P = 1 Illustrated 1 Delim1

Controller output = 300

From the above example, we can see that when I directly call the object, I can achieve encapsulation, setting, viewing, etc., pay attention to the need for manual call deletion, otherwise it is prone to memory leaks. The survival time of the object is the time before we programmers release it.

Here is the way of using heap, which is prone to memory overflow. if it is a single-chip microcomputer and other units with small resources, you can use other ways to construct the object, such as the following: the survival time of the object is the end time of the main function. The compiler releases the resources of the object for us, so we don't need to release it on our own initiative.

# include "stdio.h" # include # include / / Controller object / / Controller object Properties typedef struct {int input;/* controller input * / int ouput;/* controller output * / int paired parameterology control debugging parameters * / int Sum_error;/* total deviation, positioned PID integral related parameters * / int Last_error / * Last deviation, parameters related to positional PID integration * /} controller;// construct object, initialize void Ctor_controller (controller * const Me) {/ / clear memset (Me,0,sizeof (controller));} / delete object void Del_ontroller (controller * const Me) {;} / / set controller parameter void Write_controller (controller * const Me,int P drawing int I int D) {Me- > paired parameterized P; Me- > I_parameter=I Me- > const Me,int parameterized D;} / / read the value of the controller parameter controller Read_controller (const controller * const Me,int P drawing int I drawing int D) {return (* Me) } / / calculate the controller output. It doesn't matter if you don't understand the details. You only need to know that the input deviation is deviation, and you will output a calculation result. This result can help control / / as to how the deviation defines when the PID controller is needed, you will know int Out_controller (controller * const Me,int input) {float iIncpid=0; int now_error=input;// current deviation Me- > Sum_error+=input. / / Product component limiting, mode integration over-saturation if (Me- > Sum_error > 500) {Me- > Sum_error = 500;} if (Me- > Sum_error)

< -500) { Me->

Sum_error =-500;} Me- > ouput=Me- > P_parameter * input / / P + Me- > I_parameter * Me- > Sum_error / / I + Me- > D_parameter * (now_error-Me- > Last_error); / / D Me- > Last_error=now_error / / Storage error, used to calculate return (Me- > ouput) next time; / / return the calculated value} int main () {controller test; controller read_val; / / construct, create an object Ctor_controller (& test); / / set the value of the object Write_controller (& test,1,1,1) / / View the value of the object read_val=Read_controller (& test,1,1,1); printf ("object P =% d ID% d dating% d\ r\ n", read_val.P_parameter,read_val.I_parameter,read_val.D_parameter); / / call the controller once: printf ("controller output =% d\ r\ n", Out_controller (& test,100));} Code implementation-Advanced version

To the advanced version, we can see the complete implementation of the encapsulation, which has the properties and behavior of the object. Here we access the behavior of the object through the function pointer, and we can access the behavior of the object through the function pointer.

So how does the specific behavior come true? The implementation is to access the function through the function pointer in the function table, so as to realize the call of different functions and realize the behavior of the object.

So let's take a look at the code implementation, and then analyze the pointer to see how the function is implemented.

Header file: defines the properties and behavior of the object

# ifndef _ _ OOP_H#define _ _ OOP_H// controller object struct controller_vtbl;typedef struct {/ / object attributes int input;/* controller input * / int ouput;/* controller output * / int packs parameterno control parameters * / int Sum_error;/* total deviation, positioned PID integral related parameters * / int Last_error / * Last deviation, positional PID integral related parameters * / / object behavior pointer, access the table where the behavior of the object is located by the pointer struct controller_vtbl * vptr;} controller;//, define the behavior of the object here, by defining the function pointer to the pointer struct controller_vtbl {controller * (* Ctor_controller) (void) that needs to implement the behavior of the object Void (* Del_controller) (controller * const Me); controller (* Read_controller) (const controller * const Me); void (* Write_controller) (controller * const Me,int P minint I int D); int (* Out_controller) (controller * const Me,int input);}; / / object behavior function controller * Ctor_controller (void); void Del_controller (controller * const Me) Controller Read_controller (const controller * const Me); void Write_controller (controller * const Me,int Pjinint I int D); int Out_controller (controller * const Me,int input); # endif

Source file:: the implementation of the behavior attribute of the concrete function is here.

/ / start to construct the object, since it is a controller, the object must have input, output, debug parameter / / attribute: parameter value, input value, output value / / behavior is: set parameters, view parameters, calculate output according to input, construct object Delete object / / attribute: implement # include "stdio.h" # include # include # include "temp.h" / / construct object with structure, initialize controller * Ctor_controller (void) {controller * ptr Struct controller_vtbl * table; ptr= (controller *) malloc (sizeof (controller)); table= (struct controller_vtbl *) malloc (sizeof (struct controller_vtbl)); / / Zero memset (ptr,0,sizeof (controller)); table- > Ctor_controller=&Ctor_controller; table- > Del_controller=&Del_controller; table- > Out_controller=&Out_controller; table- > Write_controller=&Write_controller; table- > Read_controller=&Read_controller Ptr- > vptr=table; return ptr;} / / Delete object / destructed object void Del_controller (controller * const Me) {if (Meteorological null) {free (Me- > vptr); free (Me);}} / / set controller parameter void Write_controller (controller * const Me,int Ppenint I point D) {Me- > paired parameterized P; Me- > Icoded parameterized I; Me- > D_parameter=D } / / read the value of the controller parameter controller Read_controller (const controller * const Me) {return (* Me) } / / calculate the controller output. It doesn't matter if you don't understand the details. You only need to know that the input deviation is deviation, and you will output a calculation result. This result can help control / / as to how the deviation defines when the PID controller is needed, you will know int Out_controller (controller * const Me,int input) {float iIncpid=0; int now_error=input;// current deviation Me- > Sum_error+=input. / / Product component limiting, mode integration over-saturation if (Me- > Sum_error > 500) {Me- > Sum_error = 500;} if (Me- > Sum_error)

< -500) { Me->

Sum_error =-500;} Me- > ouput=Me- > P_parameter * input / / P + Me- > I_parameter * Me- > Sum_error / / I + Me- > D_parameter * (now_error-Me- > Last_error); / / D Me- > Last_error=now_error / / Storage error, used to calculate return (Me- > ouput) next time; / / return the calculated value} int main () {controller * test; controller read_val; / / construct, create an object and return the object pointer test=Ctor_controller () / / set the value of the object test- > vptr- > Write_controller (test,1,1,1); / / View the value of the object read_val=test- > vptr- > Read_controller (test); printf ("object P =% d I% d dating% d\ r\ n", read_val.P_parameter,read_val.I_parameter,read_val.D_parameter) / / call the controller once: printf ("Controller output =% d\ r\ n", test- > vptr- > Out_controller (test,100)); / / Delete / destroy an object test- > vptr- > Del_controller (test);}

Running result:

Object P = 1 Illustrated 1 Delim1

Controller output = 300

As you can see, this time the operation object is not to call the function directly, but to access the specific function through the pointer, and the pointer is in the created object, so that we can access its behavior directly through the object.

The later implementation of polymorphism also uses function pointers, in which pointers and behavior tables have their own names, that is, virtual pointers and virtual tables.

At this point, the study of "what is the encapsulation in C language object-oriented programming" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report