[C++] Classes and objects (middle)

5a2585dded9b416fb4ea58637b42ed39.png

  Yan-yingjie's homepage

Awareness of the past, not remonstrance, knowing the future, can be pursued  

C++ programmer, 2024 electronic information graduate student


The 6 default member functions of the class

          If there are no members in a class, it is referred to as an empty class, but an empty class does not mean that there is nothing in the true sense. The compiler will generate the above default 6 functions by default, which we call default member functions.

     

Constructor

          characteristic

                The constructor is a special member function. It should be noted that although the constructor is called construction, the main task of the constructor is not open space to create objects , but to initialize objects

        Its characteristics are as follows:

  •  The function name is the same as the class name        
  •  No return value, no need to write return value
  •  The compiler automatically calls the corresponding constructor when the object is instantiated
  •  Constructors can be overloaded

        Auto-generated constructors do not initialize built-in types by default

        The constructor is a special member function with the same name as the class name, which is automatically called by the compiler when creating a class type object .

To ensure that each member has a suitable initial value and is only called once throughout the entire life cycle of the object.

destructor

         Destructor: Contrary to the function of the constructor, the destructor does not complete the destruction of the object itself, and the local object destruction is done by the compiler. When the object is destroyed, it will automatically call the destructor to complete the cleanup of resources in the object .
        characteristic
        
               A destructor is a special member function whose characteristics are as follows:
        1. The name of the destructor is to add the character ~ before the class name.
        2. No parameters and no return type.
        3. A class can have only one destructor. If not explicitly defined, the system will automatically generate a default destructor. Note: Destructors cannot be overloaded
        4. When the object life cycle ends, the C++ compilation system automatically calls the destructor

       With constructors and destructors, we are not afraid to forget to write initialization and destruction functions

        

class Date
{
public:
	void Print()
	{
		cout<<_year<<"-"<<_month<<"-"<<_day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;
	Date d2;
	d1.Print();
	return 0;
}

         The compiler generates constructors by default, built-in types are not processed, and custom types will call his default construction (some compiled

The device will handle it by itself)

        In general, if there are built-in type slave members, you need to write your own constructor, which cannot be generated by the compiler. All

All are members of custom types, you can consider letting the compiler automatically generate

        Solution:

class Date
{
public:
	void Print()
	{
		cout<<_year<<"-"<<_month<<"-"<<_day << endl;
	}
private:
//C++11支持,这里不是初始化,因为这里只是声明
//这里给的是默认的缺省值,给编译器默认构造函数用的
	int _year = 1;
	int _month = 1;
	int _day = 1;
};

int main()
{
	Date d1;
	Date d2;
	d1.Print();
	return 0;
}

        in conclusion:

                1. Under normal circumstances, there are dynamically applied resources, and we need to write the destructor by ourselves

                2. There is no dynamically applied resource, we don't need to write a destructor

                3. All are custom type structures, and these types define default structures

question:

           What is the difference between struct and class in C++?

              C++ needs to be compatible with C language, so struct in C++ can be used as a structure, and struct in C++ can also

It can be used to define a class, which is the same as the class definition class, the difference is that the class defined by struct, the default access permission is public,

The class defined by class defaults to private

        Explanation of access qualifiers:

        1. Members modified by public can be directly accessed outside the class

        2. Protected and private modified members cannot be directly accessed outside the class

        3. The scope of access rights is from the position where the access qualifier appears until the next access qualifier appears

        4. If there is no access qualifier behind, it will end until the end of the } class

        How are structures aligned? Why memory alignment?

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

        ②.Other member variables must be aligned to an address that is an integer multiple of a certain number (alignment number)

        ③. The total size of the structure is: an integer multiple of the maximum alignment number

        ④. In the case of a nested structure, 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 multiple of all maximum alignment numbers (including the alignment number of the nested structure) .

        this pointer

                derivation of this pointer

                        

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

class Date
{
public:
	void Init(int year,int month,int day)
	{
		_year = year;
		_month = month;
		_day = day;
	
	}
	void Print()
	{
		cout<<_year<<"-"<<_month<<"-"<<_day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1;
    Date d2;
    d1.Init(2023,7,6);
	d1.Print();
    d2.Init(2022,7,6);
    d2.Print();
	return 0;
}

        Question: There are two member functions Init and Print in the Date class, and there is no distinction between different objects in the function body, so when d1 calls the Init function, how does this function know to set the d1 object instead of the d2 object?

        C++ introduces the this pointer to solve this problem, that is: the C++ compiler adds a hidden pointer parameter 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), All member variable operations in the function body are 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.

        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 a value

                2. Can only be used inside member functions

                3. This pointer is essentially a formal parameter of a member function. When an object calls a member function, the address of the object is used as the actual

parameter passed to the this 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, the compiler uses the ecx register to automatically

Dynamic transfer, no user transfer required

                C++ is divided into basic types/built-in types (int, char, pointer, float, etc.), custom types (struct, class, etc.)

defined type), the built-in type will not be processed, and the custom type will call its default constructor

                The this pointer cannot be explicitly passed between formal parameters and actual parameters, but it can be used explicitly in functions

                After the function is instantiated, it will be called automatically

copy constructor

        concept

                 Copy constructor: There is only a single formal parameter, which is a reference to the object of this class type (usually const decoration), which is automatically called by the compiler when creating a new object with an existing class type object.

        feature
        The copy constructor is also a special member function with the following characteristics :
        
        1. The copy constructor is an overloaded form of the constructor .
        2. The parameter of the copy constructor is only one and must be a reference to a class type object , and the compiler directly reports
Wrong , because it will cause an infinite recursive call.

  

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	// Date(const Date& d)   // 正确写法
	Date d2(Date d) 
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1;
	//拷贝构造是一种特殊的构造函数,只不过是调用同类型对象进行拷贝
	//自定义类型传参必须进行拷贝构造
	Date d2(d1);

	return 0;
}

        If not explicitly defined, the compiler will generate a default copy constructor. The default copy constructor objects are stored in memory by
The byte order completes the copy, which is called a shallow copy, or a value copy.

        

class Time
{
public:
	Time()
	{
		_hour = 1;
		_minute = 1;
		_second = 1;
	}
	Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
		cout << "Time::Time(const Time&)" << endl;
	}
private:
	int _hour;
	int _minute;
	int _second;
};
class Date
{
private:
	// 基本类型(内置类型)
	int _year = 1970;
	int _month = 1;
	int _day = 1;
	// 自定义类型
	Time _t;
};
int main()
{
	Date d1;

	// 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
	// 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构
	造函数
		Date d2(d1);
	return 0;
}
         Note: In the default copy constructor generated by the compiler, built-in types are directly copied in bytes, while custom
A defined type is copied by calling its copy constructor.

        

        

        

Guess you like

Origin blog.csdn.net/m0_73367097/article/details/131327271