当前位置:网站首页>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 .
边栏推荐
- Labelme cannot open the picture
- Multi card training in pytorch
- 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
- 11. Backup switch
- TypeError: Cannot read properties of undefined (reading ‘then‘)
- [common commands]
- C language: structure simple syntax summary
- DASCTF2022.07赋能赛
- [express connection to MySQL database]
- Log configuration logback
猜你喜欢
The third ACM program design competition of Wuhan University of Engineering
不会就坚持67天吧 平方根
Basic operation of queue
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
visio画网格
C language force buckle question 61 of the rotating list. Double ended queue and construction of circular linked list
6. Pytest generates an allure Report
不会就坚持69天吧 合并区间
11. Backup switch
Pytoch automatic mixing accuracy (AMP) training
随机推荐
Pytoch automatic mixing accuracy (AMP) training
Log configuration logback
9.延迟队列
Oracle update and delete data
kotlin的List,Map,Set等集合类不指定类型
No, just stick to it for 59 days
C language: structure simple syntax summary
Flutter实战-请求封装(二)之dio
Christmas tree web page and Christmas tree application
C language: talking about various complex statements
redux快速上手
Star a pathfinding in LAYA
使用容器部署Jenkins
Kotlin's list, map, set and other collection classes do not specify types
[common commands]
[C language] PTA 7-91 output leap year
leetcode 686.重复叠加字符串 KMP方法(C语言实现)
不会就坚持67天吧 平方根
Don't insist on 66 days. Weight generates random numbers
异常解决:cococaption包出现找不到edu.stanford.nlp.semgraph.semgrex.SemgrexPattern错误