C++ Elementary Classes and Objects (Part 2)

Table of contents

1. Copy constructor

1.1 What is a copy constructor?

1.2 Why is it necessary to quote?

1.3 Using copy constructor

1.4 What is the use of copy constructor?

2. Operator overloading

2.1 What is operator overloading?

2.2 Things to know before trying

2.3 Common operator overloading

2.3.1+= operator overloading

2.3.2+Operator overloading

2.3.3 Prefix ++ and postfix ++ operator overloading

3. Preview of next issue


Preface: In each issue of the C++ Beginner Series, bloggers will use simple and plain language to share the corresponding knowledge with everyone, striving to be understood by everyone. The C++ Beginner Series will continue to be updated, and will be updated from time to time during the school year. But there will always be more

1. Copy constructor

1.1 What is a copy constructor?

The copy constructor is a reconstruction of the constructor, which means it has nothing to return and is also created to construct members.

The copy constructor has only a single formal parameter,This formal parameter is a reference to an object of this class (usually const modified), when using It is automatically called by the compiler when creating a new object from an existing class type object.

1.2 Why is it necessary to quote?

Why does this formal parameter have to be a reference to the class object? Can't I directly pass the target to be copied? Isn't it the same operation? The following code will perfectly match your idea

#include<iostream>
using namespace std;
class Date
{
public:

	Date(int year = 1,int month=1,int day=1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	Date(Date date)
	{
		_year = date._year;
		_month = date._month;
		_day = date._day;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{

}

Today's compilers are very smart and directly prevent your infinite recursion behavior. Why does infinite recursion occur?

Let's put it this way, suppose you have a Date d and your test function, and you want to pass d to the test function, so the compiler will call this copy constructor, and when you call this copy constructor, you will generate a file called date formal parameter, and this formal parameter happens to be a variable of Date type, then it will also go to the copy constructor, so the copy constructor calls the copy constructor, and then calls the copy constructor...

1.3 Using copy constructor

Simple copy and print it. It will be better if you type the code yourself. Don’t just look at it. As for why you need to add const is because the variables we pass are passed What is copied will not be modified    Adding const is to avoid the occurrence of some low-level errors, such as modifying the copied object, and at the same time increasing the readability of the code.

1.4 What is the use of copy constructor?

After learning this, everyone probably understands that the copy constructor simply copies the target content to the newly defined object. So is it useful? This is a doubt of many beginners. In fact, it is not only useful, it is Very useful.

For example, the copy constructor of the date class we implement now actually only involves a simple value copy. In the later stage, what kind of stack, heap, binary tree and other things will we use? If we still simply copy the value , isn’t the thing we copy just an empty shell? We have to adopt some methods to implement deep copy, that is, the kind of copy that copies all the values ​​in the stack, so that we can ensure that the two things are exactly the same. can achieve the desired effect.

2. Operator overloading

2.1 What is operator overloading?

In fact, many friends must have had this kind of trouble when using C language. My structure + structure cannot be played. I have to use . or -> to obtain the structure members before I can do it. It’s too laborious to operate the members inside. Even if I write a function, I have to do d3=addition(d1,d2);Can’t d1+d2    < a i=2> is achievable in C++. This operation is called operator overloading, which is to supplement the definition of operators.

2.2 Things to know before trying

operator is used for operator overloading, such as the overloading of + operator. When writing the overloading part, we have to add operator before it. This formula can be used to explain: Return type+operator+overloaded operator (parameter)

Operator overloading can be written inside the class or outside the class    When written outside the class, we often use an operation called friends. This operation The general meaning is to make you, the thing outside the class, become a friend of my class, so the thing outside your class can access the content in the private part of the class. I will not go into details about friends here, and will be explained later.

Some friends may have some problems, so we can directly remove private, or not define member variables in private. What I want to say is that this is a bit of a waste of time, because part of the reason why there are classes in C++ is because the functions and variables of multiple structures are too confusing. If you do it your way, then this class Everyone can operate the member variables of , so what are the rules and what is the meaning of creating this class?

Therefore, the method used by bloggers when overloading operators is to overload operators in the class, so that private member variables can be accessed and the rigor of the code can be ensured.

Note:
1. New operators cannot be created by connecting other symbols: such as operator@ 
2. Overloaded operators must have A class type parameter
3. The meaning of operators used for built-in types cannot be changed, for example: the built-in integer + cannot change its meaning
4 .When overloaded as a class member function, its formal parameters appear to be 1 less than the number of operands, because the first parameter of the member function is hidden this 5. .* :: sizeof ?: . Note that the above five operators cannot be overloaded. This often appears in multiple-choice questions in written exams. Just memorize these 5 by rote and you’ll be fine.

2.3 Common operator overloading

2.3.1+= operator overloading

Goal: To achieve a date + number of days, the date is modified to the date of how many days have passed

Many people will write like this for the first time, and the compiler reports an error because has an extra this pointer and has reached the operation of the ternary operator   So we only need to remove Date d1, but because of the existence of this pointer, we can still operate on this variable.

Before implementing this, we can write a GetMonthDay function to get the number of days in January. It is worth noting that February is 29th in leap years. Next, let’s talk about the implementation idea. Our return value is best set to Date& , because the target of the += operation still exists in main after leaving the function scope, so using the return value of the Date& type can improve the efficiency of the compiler.

You can first add day to the _day of the target, which will facilitate subsequent carry. For example, 2023-11-16 +100 will be processed into 2023-11-116 first, and then the carry will be carried out through the specific carry data obtained by GetMonthDay. However, this can be achieved through a loop. When _day>GetMonthDay means a carry is required, so this can be used as a condition for whether the loop continues. Subsequent implementations only need to pay attention to some details, for example, when the month is 12 Enter 1 or something like that.

	int GetMonthDay(int year, int month)
	{
		int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
		//之所以是13是为了更加符合日期的返回,一月就返回数组下标为1的值
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
		{
			return 29;
		}
		return arr[month];
	}
	Date& operator +=(int day)
	{
		_day += day;
		while (_day > GetMonthDay(_year,_month))
		{
			_day -= GetMonthDay(_year, _month);
			_month++;
			if (_month>12)
			{
				_month = 1;
				_year++;
			}
		}
		return *this;
	}

test:

2.3.2+Operator overloading

After having the += operator, the + operator is easy to operate, just reuse it. 

The reason for using temporary variables is that the + operator does not change the value of the original variable. For example, a=b+100; b here will not be modified.

	Date operator+(int day)
	{
		Date tmp = *this;
		tmp += day;
		return tmp;
	}

2.3.3 Prefix ++ and postfix ++ operator overloading

In C++, if we want to overload prefix ++ and postfix ++, you will be surprised to find that their operator names are actually exactly the same. How to distinguish them? In fact, the founder didn't have a good solution. He made a special treatment for this place, just like the special situations we encountered when doing OJ questions, we dealt with them individually. The founder did the same thing.He stipulated that the difference between prefix++ and post++ is that the parameters of post++ are of type int

What's the meaning? It's almost like this. The one in front of operator++() and operator++(int) represents the prefix ++, and the one behind it represents the postfix ++. So why is it int and not float? All I can say is that this is a coincidence. The founder wanted to use int to distinguish it, that's all.

With + and += implemented, just reuse them directly.

3. Preview of next issue

Probably tomorrow, the blogger will come up with a detailed explanation of date class implementation, which will talk about friend operations. I look forward to your arrival QAQ 

Guess you like

Origin blog.csdn.net/fq157856469/article/details/134440992