当前位置:网站首页>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 .
边栏推荐
- Coding questions encountered in the interview
- Not for 58 days. Implement prefix tree
- [material delivery UAV] record (ROS + Px4 + yolov5 + esp8266 + steering gear)
- Not for 63 days. The biggest XOR
- Installation and use of stm32cubemx (5.3.0)
- 14.haproxy+keepalived负载均衡和高可用
- 不会就坚持61天吧 最短的单词编码
- Pyscript cannot import package
- Make a virtual human with zego avatar | virtual anchor live broadcast solution
- 不会就坚持70天吧 数组中第k大的数
猜你喜欢

你真的会写Restful API吗?

Vscode one click compilation and debugging

STL source code analysis (Hou Jie) notes -- Classification and testing of stl containers

Not for 63 days. The biggest XOR

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

9.延迟队列

LeetCode_ Stack topics

Not 67 days, square root

使用容器部署Jenkins
![Understand the Internet giant [the war between China and Taiwan] and the development thinking of China and Taiwan](/img/6c/f24407133663c0e19d6fa05c611341.png)
Understand the Internet giant [the war between China and Taiwan] and the development thinking of China and Taiwan
随机推荐
Vscode one click compilation and debugging
Not for 58 days. Implement prefix tree
LeetCode_ Stack topics
用 ZEGO Avatar 做一个虚拟人|虚拟主播直播解决方案
Mongo shell interactive command window
11. Backup switch
oracle 更新和删除数据
It won't last for 70 days. The k-largest number in the array
Not for 60 days, magical dictionary
Not 67 days, square root
[C language] PTA 7-91 output leap year
Idea small settings
Niuke IOI weekly 27 popularity group
What is the use of meta-info?
es6和commonjs对导入导出的值修改是否影响原模块
Not for 61 days. The shortest word code
Installation and use of stm32cubemx (5.3.0)
settings.xml
异常解决:cococaption包出现找不到edu.stanford.nlp.semgraph.semgrex.SemgrexPattern错误
Machine vision Series 1: Visual Studio 2019 dynamic link library DLL establishment