当前位置:网站首页>Classes and objects (II)
Classes and objects (II)
2022-07-29 04:32:00 【Small clock HHH】
List of articles
The six default member functions of the class
If there are no members in a class , It is called empty class for short . Is there nothing in the empty class ? It's not , Any class we don't write , Will automatically generate the following 6 Default member functions .
// Empty class
class Date
{
};

What the constructor does is initialize , What the destructor does is clean up , Copy construction is copy , Assignment overload is also a copy , But the scenarios are different , The last address overload is rarely used .
Constructors
A constructor is a special member function , Same name as class name , It is automatically called by the compiler when creating class type objects , Make sure every data member has A suitable initial value , And only called once in the object's life cycle . Constructors are special member functions , It should be noted that , Although the name of the constructor is called constructor , But here's the thing The main task of constructors is not to create objects in open space , Instead, initialize the object .
Features of constructors :
- Function name and class name are the same .
- No return value .
- The corresponding constructor is automatically called when the object is instantiated .
- Constructor can overload
Object will call the corresponding constructor to initialize .
class A
{
public:
// Parameterless constructor
A()
{
_a = 2;
}
// Constructor with parameters
A(int a)
{
_a = a;
}
void Print()
{
cout << _a << endl;
}
private:
int _a;
};
int main()
{
A a1;
A a2(10);
a1.Print();
a2.Print();
return 0;
}

This is the constructor written in the class to initialize , But what if you don't write a constructor ?
If no constructor is explicitly defined in the class , be C++ The compiler will automatically generate a parameterless default constructor , Once explicitly defined by the user, the compiler will no longer generate .
class A
{
public:
void Print()
{
cout << _a << endl;
}
private:
int _a;
};
int main()
{
A a1;
a1.Print();
return 0;
}

For this code , Run discovery is to output random values , Is the constructor generated by the compiler by default useless ?
The answer is No , Just look at the next code .
class B
{
public:
// class B Constructor for
B()
{
_x = 1;
_y = 2;
}
private:
int _x;
int _y;
};
class A
{
public:
private:
int _a;
// class B Defined objects
B _b;
};
int main()
{
A a1;
return 0;
}

The above initialization can be observed through debugging , You can find _a Not initialized , But the object _b But it was initialized , Why is that ?
Add : Here we need to add a knowledge about types .C++ Divide types into built-in types ( Basic types ) And custom types . A built-in type is a type that has been defined by the syntax : Such as int/char..., Custom types are what we make class/struct/union Self defined type .
No constructor is shown
We don't write constructors , The compiler generates a default constructor , An eccentric treatment is made here :
- Built in types do not handle .
- A custom type calls its own constructor .
Add : Parameterless constructors and fully default constructors are called default constructors , And the default constructor can only have one . Be careful : Parameter free constructor 、 Full default constructor 、 We didn't write the constructor generated by the compiler by default , Can be considered as the default constructor , The constructor that is not generated by the compiler by default is called the default constructor .
Destructor
Destructor : Contrary to constructor function , Destructors do not complete the destruction of objects , The destruction of local objects is done by the compiler . and The destructor is automatically called when the object is destroyed , Complete some resource cleanup of the class .
Characteristics of destructors :
- The destructor name is preceded by the character
~. - No parameter, no return value .
- A class has only one destructor . If not explicitly defined , The system will automatically generate the default destructor .
- At the end of the object's lifecycle ,C++ The compiler system automatically calls the destructor .
Like constructors, they are called automatically , Automatically call... At the end of the object's life cycle . So what is the function of destructors ? General classes don't seem to work , But it's like stack In such a class , There will be dynamic space , So we need to deal with it in the destructor .
There is no display defining destructors
Destructors are the same as constructors , Don't write destructors , The compiler generates a default destructor , The compiler also makes an eccentric treatment here :
- Built in types do not handle .
- A custom type calls its own destructor .
copy constructor
Copy constructor is to create an object through an object , The copy constructor is also a special member function , Its features as follows :
- copy constructor Is an overloaded form of the constructor .
- Copy constructor There is only one parameter And Reference must be used to pass parameters , Use The value passing method will cause infinite recursive calls .
Note the second point that the copy constructor should use references when passing parameters , Otherwise, infinite recursion will occur .
class A
{
public:
A(int a)
{
_a = a;
}
// If this is not a reference
A(A a)
{
_a = a._a;
}
private:
int _a;
};
int main()
{
A a1(10);
A a2(a1);
return 0;
}

Infinite recursion problem of copy construction
The compiler will report an error if you don't need to reference the passed parameter , Because there will be a problem of infinite recursion .
When an argument passes a formal parameter , This is actually a copy , Then call the copy construct , Empathy , Continue to call the copy construct , It will cause an infinite recursion error , So you need to use references here to pass parameters , Prevent infinite recursion .
It is best to add const
Since you use references to pass parameters , Then we should consider the problem that the change of formal parameters leads to the change of actual parameters , So it's best to add a reference when using const, Prevent arguments from changing . about const Use , When passing parameters , When it is not an output parameter , It's better to add const, To protect .
The definition copy constructor is not shown
If the definition copy constructor is not displayed , The compiler automatically generates a default copy constructor , The copy constructor and constructor generated by the compiler by default 、 Destructors are different .
- Built in type , Byte ordered Shallow copy ( Copy in byte order , It's like memcpy).
- A custom type calls its own copy constructor to complete the copy .
Depth copy
The disadvantage of shallow copy is obvious , Shallow copy copies only pointers to an object , Instead of copying the object itself , New and old objects still share the same block of memory . But deep copy creates as like as two peas , The new object does not share memory with the original object , Modifying the new object does not change to the original object .

Defects of shallow copy
If there is a pointer in the member variable , There is a dynamic space opening operation in the constructor , Then it will be released in the destructor (free/delete) fall , In this way, the same space will be released twice .

You can see in the above figure that a1 and a2 It points to the same space ,a2 First, the destructor has _a The space pointed to frees up ,a1 If you dissect again, you will _a The space pointed to is released again , Release the same space twice , The program will crash . So for this kind of problem , So you need to make a deep copy , Open up a new space .
边栏推荐
- On quotation
- Record the Niua packaging deployment project
- Redux quick start
- What is the use of meta-info?
- Hengxing Ketong invites you to the 24th China expressway informatization conference and technical product exhibition in Hunan
- Mongo shell interactive command window
- Deep learning training strategy -- warming up the learning rate
- Pyqt5 learning pit encounter and pit drainage (1) unable to open designer.exe
- 不会就坚持65天吧 只出现一次的数字
- es6和commonjs对导入导出的值修改是否影响原模块
猜你喜欢

Make a virtual human with zego avatar | virtual anchor live broadcast solution

6. Pytest generates an allure Report

MySQL - deep parsing of MySQL index data structure

DASCTF2022.07赋能赛

不会就坚持62天吧 单词之和

Record of problems encountered in ROS learning

Realize the effect of univariate quadratic equation through JS. Enter the coefficients of a, B and C to calculate the values of X1 and x2

15.federation

6.pytest生成allure报告

Visio draw grid
随机推荐
[C language] power table of 3 generated by PTA 7-53
No, just stick to it for 59 days
DASCTF2022.07赋能赛
TypeError: Cannot read properties of undefined (reading ‘then‘)
C language: talking about various complex statements
There are objections and puzzles about joinpoint in afterreturning notice (I hope someone will leave a message)
Unity Foundation (3) -- various coordinate systems in unity
Actual combat of flutter - DIO of request encapsulation (II)
12. Priority queue and inert queue
Pytorch GPU and CPU models load each other
[c language] PTA 7-55 query fruit price
MySQL - 深入解析MySQL索引数据结构
kotlin的List,Map,Set等集合类不指定类型
Machine vision Series 2: vs DLL debugging
Semantic segmentation correlation
Not for 61 days. The shortest word code
C语言:联合体知识点总结
Won't you just stick to 62 days? Sum of words
不会就坚持62天吧 单词之和
VScode 一键编译和调试