C++ basic framework for classes and objects + complete mind map + basic exercises + in-depth details + easy-to-understand suggestions for collection


introduction

In the last chapter, we learned the basics of c++ entry. In this chapter, it may be difficult to really step into c++, but only if we keep moving forward, can we cut through the thorns and overcome the ups and downs of life!

        

Not much to say, fasten your seat belt, let's start the car (recommended to watch on computer) .


Attachment: red, the part is the key part; the blue color is the part that needs to be memorized (not rote memorization, knock more); black bold or other colors are the secondary key points; black is the description need


mind Mapping:

If you want XMind mind map, you can private message


Table of contents

1. Process-oriented and object-oriented understanding

2. Introduction of class

3. Class definition (class)

3.1 Class access qualifiers

4. Encapsulation

5. Instantiation of the class

6. Class object model

6.1 Calculating the size of a class object

7. this pointer


1. Process-oriented and object-oriented understanding

Process-oriented, object-oriented concepts:

C language is process-oriented , focusing on the process, analyzing the steps to solve the problem, and solving the problem step by step through function calls ; while C++ is based on object-oriented , focusing on the object , splitting one thing into different objects, It is done by the interaction between objects. ( Process is the steps to complete a thing, while object-oriented is oriented to people, what needs do people need )

2. Introduction of class

Knowledge points:

In c++, struct is upgraded to a class. At this time, unlike C language, we can define functions in the structure

Details (specific):

  1. In this case, the functions that implement the functions in the data structure are written separately, and in C++, because the struct is upgraded to a class, the class can directly put the functions to be implemented in the structure .

practise:

Write a class to implement the basic structure of the stack:

 #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<stdlib.h>
#include<assert.h>

using namespace std;

struct Stack
{
	//成员函数
	//在类域中不管声明的位置都能找得到
	void Init(int DefaultCapacity = 4)
	{
		a = (int*)malloc(sizeof(int) * DefaultCapacity);
		if (a == nullptr)
		{
			perror("malloc");
			return;
		}
		capacity = DefaultCapacity;
		size = 0;
	}
	void Push(int x)
	{	
		if (size == capacity)
		{
			int* ptr = (int*)realloc(a, sizeof(int) * capacity * 2);
			assert(ptr);
			a = ptr;
			capacity *= 2;
		}	
		a[size++] = x;
	}

	int Top()
	{
		assert(size);
		return a[size - 1];
	}


    // ....  就不过多的写了,此处了解语法即可


	void Destroy()
	{
		free(a);
		a = nullptr;
		capacity = size = 0;
	}
	//成员变量
	int* a;
	int size;
	int capacity;
};

int main()
{
	Stack sk;
	sk.Init(20);
	sk.Push(1);
	sk.Push(2);
	sk.Push(3);
	cout << sk.Top() << endl;//栈顶元素3
	sk.Destroy();

	return 0;
}

3. Class definition (class)

Knowledge points:

  1. The basic syntax is the same as that of struct, but with a different name ; class is the keyword to define the class, ClassName is the name of the class, and {} is the body of the class . Note that the semicolon after the end of the class definition cannot be omitted , and the content in the class body is called Members of a class : variables in a class are called attributes or member variables of a class ; functions in a class are called methods or member functions of a class
  2. grammar:

class classname

{

             //Class body, consisting of member functions and member variables

}; // Symbols are also required for structures

3.1 Class access qualifiers

Access qualifiers:

publish (public), private (private), protect (protection)

1. Members modified by public can be directly accessed outside the class
2. Members modified by protected and private cannot be directly accessed outside the class (here protected and private are similar)
3. The scope of access rights emerges from this access qualifier The position starts until the next access qualifier appears.
4. If there is no access qualifier behind, the scope will go to }, that is, the end of the class.
5. The default access permission of class is private, and struct is public (because struct is compatible with C)
 

Details when using class definitions:

  1. When the declaration and definition of member functions are all placed in the class body, it should be noted that if the member function is defined in the class, the compiler may treat it as an inline function, and the member function in the default class is an inline function
  2. When the class declaration is placed in the .h file, and the member function definition is placed in the .cpp file (sub-source management): the name of the class needs to be added before the name of the member function:: ( because the name, sex, and age in this function need sources and sources It is a class, to determine that he is the definition of a member function in a class )

Attachment: Generally, you can add m and _ to the front/back/first main of the member variable to distinguish local variables and member variables


4. Encapsulation

Knowledge points:

The three major characteristics of object-oriented: encapsulation, inheritance, polymorphism

Encapsulation definition: organically combine data and methods of manipulating data , hide object attributes and implementation details, and only expose interfaces to interact with objects ( essential encapsulation is for better management )

Instance description of package:

Explain from the perspective of C language and C++:
in c, the member variables of our structure are not private like the member variables in c++, which will lead us to directly access the data in the structure, and It works privately in c++ and we cannot access it outside the class.


5. Instantiation of the class

Knowledge points:

The process of creating an object (variable) with a class type is called class instantiation (when we create a class, the member variables in it are not actually created, they are just a declaration, and there is no actual space).

So the instantiation of a class is to open up a space for variables, and the method is also very simple: just use this class to create a variable.

Actual example:

what we wrote earlier

Here is an example of instantiation, and then the size capacity in sk is instantiated (it can also be explained with a practical example: a class is a drawing, and we use this drawing to build a real house. This house is this class (instantiation of drawing))


6. Class object model

6.1 Calculating the size of a class object

Knowledge points:

In the object, only the size of the member variable is counted (the method of calculating the structure also needs to be memory aligned), and the member function is not counted in its sizeof size (because the member function is not actually placed in the object but placed When it comes to a public area, it is like a basketball court in a community, not every family has it, but in a public place)

If you have forgotten about structure memory alignment, you can read this blog

detail:

  1. For the size of the class, it is a special case when it is an empty class (class object without member variables). At this time, the compiler will give the empty class a byte (to indicate its existence)

7. this pointer

Knowledge points:

The C++ compiler adds a hidden pointer parameter (this pointer is this) to each "non-static member function" , so that the pointer points to the current object (the object that calls the function when the function is running), and in the function body all " Member variable" operations are all accessed through this pointer. It's just that all operations are transparent to the user, that is, the user does not need to pass it, and the compiler completes it automatically (you can use examples to understand the this pointer more deeply)                                           

detail:

  1. this cannot be explicitly used in formal parameters or actual parameters, but it can be explicitly used inside the function 
  2. The type of this pointer is: class * const this
  3. The this pointer exists on the stack ( not in the object , because it is a formal parameter and will exist in the stack frame of the function call)
  4. In the vs environment, the this pointer will be placed in the ecx register to pass parameters

Learn about this pointer through examples:

//写一个日期类的类
class Date
{
public:
	void Init(int year = 1970, int month = 1, int day = 1)
	{
		_day = day;
		_month = month;
		_year = year;
	}
	void Print()
	{
		cout << _year << ' ' << _month << ' ' << _day << endl;
	}
private:
	int _day;
	int _month;
	int _year;
};


int main()
{
	Date d1;
	Date d2;
	d1.Init(2004, 9, 7);
	d2.Init(2003, 7, 7);
	d1.Print();
	d2.Print();

	return 0;
}

In the above situation, why does the Print() function not pass parameters but can correctly find the object and print the data in the object, and although there are d1. d2. in front, what can this represent?

This is actually the function of the implicit this pointer. Generally speaking, when we have determined the object in front, the operating system will automatically implement some kind of operation for us (in fact, it is to pass the address of the object, and there is a this pointer to receive The parameter passed in)

For example: we can think of   d1.Print ( ); as d1 Print ( &d1 )
and in the function as

void Print(Date *const this)

{

        cout <<this -> _year << ' ' <<this ->  _month << ' ' <<this ->  _day << endl;

}

In fact, it is very similar to some structures in our data structure, except that the classes in the c++ compiler have been simplified.


This chapter is over. To predict what will happen next, let's wait for the next chapter to break it down.

Continuously update a large number of C++ detailed content, I hope it will be helpful to you! Pay attention early and don't get lost!

Guess you like

Origin blog.csdn.net/ZYK069/article/details/130290618