Classes and Objects [1] Introduction

Introduction (first understanding of object-oriented)

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;
C++ is based on object-oriented, focusing on the object, splitting one thing into different objects, relying on Interaction between objects is done.

For example, the operation of washing clothes, for the process-oriented C language, is to be implemented step by step according to the logic of the washing process: at
insert image description here
most, multiple steps of putting laundry detergent into a function are encapsulated, and a loop is written for multiple washing operations . In short, it is aimed at the process of washing clothes.

But for object-oriented C++, the process of washing clothes can be implemented according to the interaction between several encapsulated objects. For example, it is divided into people, clothes, laundry detergent and washing machine:
insert image description here
washing clothes only requires people to put clothes and laundry detergent into the washing machine, and the washing machine can perform the operation. Some washing machine objects can also automatically add laundry detergent. At this time, the laundry detergent is an internal object of the washing machine. In short, it is aimed at the objects involved in washing clothes.

It is not difficult to find that the object-oriented operation process is simpler and more efficient than the process-oriented operation process. In other words, object-oriented programming is a relatively advanced programming method.

classes and objects

Only variables can be defined in the C language structure. In C++, not only variables can be defined in the structure, but also functions can be defined:

struct Stack
{
    
    
	int* _data;
	int _top;
	int _capacity;

	void init();	
	void push();
	void pop();
	void destory();
};

The stack implemented in C language has only variables in the structure, and the variables in the structure are manipulated through functions; while the C++ stack structure can define functions, which is actually a class. Struct can be used to define classes, and there is a special keyword in C++ classto define classes:

definition

The format of a class definition class is as follows:

class Classname
{
    
    
	//类的主体(成员变量与成员函数)
};

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.
The contents of the class body are called members of the class: variables in the class are called attributes or member variables of the class; functions in the class are called methods or member functions of the class.

Class access restriction and encapsulation

Combining the properties and methods of an object with a class is encapsulation, and by accessing the details of the hidden properties and methods, only the interface is provided to the user, making it easier for the user to use the class:

There are three access qualifiers: public(public), protected(protected), private(private):

class Classname
{
    
    
public:
	//公共权限:类内可以访问,类外可以访问;
protected:
	//保护权限:类内可以访问,类外不可以访问(子类可以访问);
private:
	//私有权限:类内可以访问,类外不可以访问(子类不可以访问);
};

It is not difficult to find that because a class needs to provide an interface to the user and hide attributes, the member functions of the class are generally placed in the public domain, and the member variables are placed in the private domain.

have to be aware of is:

  1. The scope of access rights starts from the position where the access qualifier appears until the next access qualifier appears. If there is no access qualifier behind, the scope will reach }, that is, the end of the class ;
  2. The default access permission of class is private, and struct is public (because struct is compatible with C).

Two ways of class definition

When defining a class, there are two ways: the declaration and definition of the function are placed together in the class or the declaration and definition of the function are separated, the declaration is placed in the class, and the function definition is placed in the .cpp file:

It should be noted that if a member function is defined in a class, this function will be regarded as an inline function by default (here simply write a date class example):

class Date
{
    
    
public:

	void InitDate(int year = 2023, int month = 2, int day = 10)
	{
    
    
		_year = year;
		_month = month;
		_day = day;
	}
	Date& AddDate(int day)
	{
    
    
		_day += day;
		while (_day > GetMonthDay(_year, _month))
		{
    
    
			_day -= GetMonthDay(_year, _month);
			_month++;
			if (_month > 12)
			{
    
    
				_year++;
				_month = 1;
			}
		}
		return *this;
	}
	int GetMonthDay(int year, int month)
	{
    
    
		int monthdays[13] = {
    
     0,31,28,31,30,31,30,31,31,30,31,30,31 };
		if ((month == 2) && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
    
    
			monthdays[month] = 29;
		}
		return monthdays[month];
	}
private:
	int _year;
	int _month;
	int _day;
};

If the declaration is separated from the definition, the definition is required when defining the function 类名::函数名:

class Date
{
    
    
public:
    void InitDate(int year = 2023, int month = 2, int day = 10);
	Date& AddDate(int day);
	int GetMonthDay(int year, int month);
private:
	int _year;
	int _month;
	int _day;
};

void Date::InitDate(int year = 2023, int month = 2, int day = 10)
{
    
    
	_year = year;
	_month = month;
	_day = day;
}
Date& Date::AddDate(int day)
{
    
    
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
    
    
		_day -= GetMonthDay(_year, _month);
		_month++;
		if (_month > 12)
		{
    
    
			_year++;
			_month = 1;
		}
	}
	return *this;
}
int Date::GetMonthDay(int year, int month)
{
    
    
	int monthdays[13] = {
    
     0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if ((month == 2) && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
	{
    
    
		monthdays[month] = 29;
	}
	return monthdays[month];
}

When defining a class, it is recommended to use the second method, and define public member functions before private member variables .

Class instantiation and class object size

The class defined above is just a class type, which is equivalent to the blueprint of the house, and does not open up space in memory.
The process of creating an object with a class is called the instantiation of the class, and the instantiated object occupies a specific memory space.
The class name is the type name of the class type. A class type can instantiate multiple class objects, such as the date class above:

int main()
{
    
    
    //实例化三个类对象
	Date d1;
	Date d2;
	Date d3;
	//对三个类对象调用其成员函数进行初始化
	d1.InitDate();
	d2.InitDate(2023, 5, 14);
	d3.InitDate(2000, 1, 1);
	return 0;
}

The above content is not difficult to understand, but since the member functions are also included in the class object, how should the size of the class be calculated?
In the C language part, we learned how to calculate the size of the structure, and the structure follows the memory alignment rules when allocating memory:
Click me to see the detailed explanation of the memory alignment of the structure

The size of the class also follows the rules of memory alignment, but for member functions, although it is encapsulated in the class, it does not occupy the space of the class object. Only one copy of the member function is saved in the code segment, and only member variables are saved in the class object :

int main()
{
    
    
	Date d1;
	cout << sizeof(d1) << endl;
	return 0;
}

insert image description here
Therefore, the size of the above-mentioned Date class object d1 only includes three int-type member variables, and the size is 12 bytes according to memory alignment.

For the empty class, there will be a byte space to distinguish.

this pointer

As mentioned above, private member variables are accessible inside the class. For example, the results of adding days to different classes are different:

int main()
{
    
    
	//类实例化
	Date d1;
	Date d2;
	//类初始化
	d1.InitDate();
	d2.InitDate(2023, 5, 14);
	//不同的日期类对象+100天
	d1.AddDate(100);
	d2.AddDate(100);
	return 0;
}

insert image description here
insert image description here
So how does the member function know which object is called, and get the member variables of the class and operate on them?

This is because when we call a member function, we are actually calling its member function for an object. There is actually an implicit thispointer in the parameter list of the member function of the class object, which is on the left side of the parameter list .
The this pointer is the pointer of the object that calls the member function, and its function is to help the member function call the member variable. In fact, the AddDate function above is essentially this:

//Date& Date::AddDate(Date *const this, int day); //错误代码:this指针必须隐式传参

Inside the function, accessing member variables is implemented like this:

{
    
    
	this->_day += day;
	while (this->_day > GetMonthDay(this->_year, this->_month))
	{
    
    
		this->_day -= GetMonthDay(this->_year, this->_month);
		++(this->_month);
		if (this->_month > 12)
		{
    
    
			++(this->_year);
			this->_month = 1;
		}
	}
	return *this;
}

Although it is possible to explicitly use the this pointer to access member variables, such code is ugly and not concise.

The characteristics of this pointer:

  1. The type of this pointer: class type * const, that is, in member functions, the this pointer cannot be assigned;
  2. Can only be used inside member functions;
  3. The this pointer is essentially the formal parameter of the member function. When the object calls the member function, the object address is passed as the actual parameter to the this formal parameter. So 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.

Summarize

In this article, a preliminary understanding of classes and objects, including definition, instantiation and this pointer. Next, we will continue to introduce the relevant knowledge of classes and objects in depth. I hope you will continue to pay attention.

If you think that I did not introduce a certain part clearly or that there is a problem with a certain part, you are welcome to raise it in the comment area

If this article is helpful to you, I hope it will be connected with one click

Hope to make progress together with you

Guess you like

Origin blog.csdn.net/weixin_73450183/article/details/130549401