Class and object first entry (c++)

Let's first understand the classes and objects in C++ from the following aspects.

1. Process-oriented and object-oriented

Before we learn C++, we must first understand what is process-oriented and what is object-oriented, so as to help us learn C++ better, let's first look at their definitions:

Process-oriented: Process-oriented is to analyze the steps required to solve the problem, and then use functions to implement these steps step by step, and call them one by one when they are used.

Object-oriented: Object-oriented is to decompose the transaction that constitutes the problem into various objects. The purpose of establishing an object is not to complete a step, but to describe the behavior of something in the whole problem-solving step. (Any real life things can be regarded as objects)

After knowing its definition, we will find that our commonly used C language is a process-oriented language, then C++ is an object-oriented language, but there is another point to say that C++ is not a pure object-oriented language, it is based on object-oriented --> both There are process-oriented and object-oriented.

2. The introduction of classes and objects

What is a class?

Class: It is used to describe the entity (object), what attributes the object has, and what function the object has. It is a custom type. After the class is defined, it cannot directly store data in the class.

What is an object?

Object: It exists in real life, the object is the concrete embodiment of the class, the object is the variable created by the class type, the object can store data. (The object can be regarded as the instantiation of the class)

Let’s take an example for everyone’s understanding: I believe that some friends have reached the age of marriage, or their family has already urged marriage. At this time, it is natural to have a girlfriend, but if you don’t have a girlfriend, you need to go on a blind date. Many cities will have them. In the "square" of offline blind date, the person who wants to blind date or their relatives and friends will print this person's information on paper for others to understand, such as: age, job, gender, height, hobbies, education, etc., And this piece of paper can be regarded as a class, which is a description of the information of that specific person, and the person corresponding to this piece of paper is an object, a real object.

3. Definition of class

1.class

class className
{
 // 类体:由成员函数和成员变量组成
 
}; // 一定要注意后面的分号

2.struct

struct className
{
 // 类体:由成员函数和成员变量组成
 
}; // 一定要注意后面的分号

There are two kinds of keywords for defining classes, one is struct and the other is class. The default access permission of class members defined by struct is public (you can see the following access qualifiers if you don’t know the access permission), and the class defined by class The default access authority is private, and there are two ways to define it. The first way is to put the class declaration and definition in the class definition. The second way: the class declaration is placed in the header file, and the class definition is placed in the original file ( We generally use method two to define).

Let's take a class as an example to illustrate:

Method 1: Put the class declaration and definition in the class body in the original file.

 Method 2: declare it in the header file and define it in the original file.

4. Encapsulation and class access qualifiers

Since we are learning C++, we must know the three major characteristics (four characteristics) of object-oriented: encapsulation, inheritance, polymorphism (if we are talking about the four characteristics, add abstraction: abstraction is the recognition of a complex thing. Knowing the process), in this article only the package is introduced.

What is encapsulation?

 Encapsulation is an organic combination of data and methods of manipulating data, hiding the attributes and implementation details of objects, and only exposing interfaces to interact with objects. (Function is a kind of encapsulation, and computers and mobile phones are also encapsulation)

How does C++ embody encapsulation?

The organic combination of data and methods of manipulating data can be regarded as a class, hiding the attributes and implementation details of the object, and only exposing the interface to interact with the object can be regarded as access rights. ( Control which members can be directly accessed outside the class )

What is an access qualifier (access right)?

It is used to limit member variables and member functions in a class. Member variables and member functions limited by public can be directly accessed outside the class. Member variables and member functions limited by protected and private cannot be directly accessed outside the class. , and also note that the scope of the access permission starts from the location where the access qualifier appears until the next access qualifier appears, see the following code for details.

1. When declaring the class in the header file, I added public access to both member variables and member functions, which means that we can directly access it outside the class, and pay attention to the role of the first public The scope is from: after to before the next public appears, and the scope of the second public is from: after to the end of the class.

 At this time, we directly accessed the input and output in the class in main. Obviously, the access was successful, and the code ran successfully without any problems.

2. When declaring the class in the header file, I added private access to member variables and member functions, which means that we cannot directly access it outside the class.

 At this time, we will find that when accessing input and output in main again, the program will report an error and generate a prompt, which shows us the role of the access qualifier.

Class scope:

In the above picture, we see that when the member functions in the class are defined outside the class, they are all in the form of classname::member function . This is because of the scope of the class. The class defines a new scope, the class All members of the class are in the scope of the class. To define members outside the class, you need to use the :: scope resolver to indicate which class scope the member belongs to.

5. Calculate the size of the class object

a. The size of the non-empty class

To ask for the size of a class object, we must first know what the class object contains. After actual verification, we found that the object only contains member variables, so the size of the object is similar to the size of the structure in the C language, as long as we pay attention to memory alignment. .

Actual verification:

Or the above code: we changed the number and type of member variables in the class many times, and then used sizeof() to directly print the size of the class and object, and found that its size is only related to member variables, and its calculation method is the same as that in C language. The size of the structure is similar, so as long as you pay attention to the memory alignment, you can find the sum of the "member variables" in the class.

So what is the specific calculation method? We must first understand the memory alignment rules in the structure.

1. The first member is at the address at offset 0 from the structure.

2. Other member variables should be aligned to an address that is an integer multiple of the alignment number.

3. Alignment = The smaller of the compiler's default alignment and the size of the member. (vs default is 8)

4. The total size of the structure is: an integer multiple of the maximum alignment number (the largest of all variable types and the default alignment parameter take the smallest).

5. If a structure is nested, the nested structure is aligned to an integer multiple of its own maximum alignment number, and the overall size of the structure is an integer of all maximum alignment numbers (including the alignment number of nested structures). times.

Then, the following rules are used to calculate it in detail.

Step 1: First find the position of the first member b, start from 0 bytes, occupy one byte, and then look at the position of the second member a, the alignment number of a is 4 (4<8), So a should start from the fourth byte and occupy four bytes backward, and then look at the position of the third member c, the alignment number of c is 8 (8 and 8 are equal to take whichever), so c starts from the first Eight bytes start to occupy eight bytes backwards, and then look at the position of the fourth member d, the alignment number of d is 4 (4<8), so d starts to occupy backwards from the sixteenth byte 4 bytes.

Step 2: Then judge the total size of the class as: the multiple of the maximum alignment number is 24.

b. The size of the empty class

Assuming that the size of the empty class is 0, when we use the empty class to create objects, there will be problems if we create multiple objects in succession, because the size of the empty class is 0, so the size of the created object is also 0, so it does not It will occupy this space, so all objects are created in this location, and their addresses are the same. How can we distinguish these objects? The answer is that there is no way to distinguish them, so C++ specifically targets empty classes to avoid this from happening. The size of the empty class is specified so that it is not 0, and this situation will naturally not happen. In general, the size of the empty class is set to 1 byte, but different compilers may also have different.

Six. this pointer

1. When we use objects to call class member functions, will we have such doubts? There is no description of objects in the member functions of our classes, so we use objects to call these methods, how do they know what to do? To operate on that object? I believe that the following introduction can help you solve this question.

First of all, let's think about how to use a structure to call a function in the C language? Generally, the address of the structure variable is passed into the function, and then the -> symbol is used to operate the data in the structure variable. The details are as follows:

The left side below is the process of calling structure variables in C language, so the function can recognize the data in the structure variable. But how to make the member function recognize the data in the object in C++ on the right? Then look down..

2. We can see the problem directly from the disassembly instruction of C++. The C++ call member function does not end after the 3 parameters are pushed on the stack, but the address of the object d is placed in the register ecx for the member function to use. Therefore, we can conclude that when a function call is made in C++, it is similar to the C language that the address of the variable is used to manipulate the data.

3. I believe that everyone should understand the role of the this pointer, let's take a look at its definition: C++ solves the problem by introducing the this pointer, and the C++ compiler adds a hidden pointer parameter to each "non-static member function" , let the pointer point to the current object (the object that calls the function), in the function body, all operations of "member variables" are accessed through this pointer, but all operations are transparent to the user, that is, the user does not You need to pass it yourself, and the compiler automatically completes it. So for the following function call, its real form can be seen as:

d1.Init(3,15, 2022 ); (object call method) At this time, the compiler will convert the call to ----> Data::Init(&d1,3,15,2022);

The location of &d1 here is the location of the this pointer, and accessing data in the function body also uses -> this symbol to resolve the address of d1 for data operations, but in C++, these operations are hidden by the compiler and are transparent. , and does not require the user to pass and parse, the compiler will help us to complete, so in the end we use C++ to write the code above, but the underlying implementation principle is the same as in the C language, but the compiler helps us to complete hidden part.

Note: 1. The scope of this is inside the class "member function".

          2. The this pointer can be null. As long as we do not access the this pointer in the member function, it will not affect the program. Next, we pass the null pointer to this, and then call the member function. At this time, we see the printed The address in this pointer is null, but the program does not crash.

So for this pointer we can summarize the following characteristics:

1. The type of this pointer: class type * const

2. Can only be used inside a "member function".

3. The this pointer is actually a formal parameter of a member function. When the object calls the member function, the object address is passed as an actual parameter to the this parameter. Therefore, the this pointer is not stored in the object.

4. The this pointer is the first implicit pointer parameter of the member function. Generally, it is automatically passed by the compiler through the ecx register and does not need to be passed by the user.

Guess you like

Origin blog.csdn.net/weixin_49312527/article/details/123527693