当前位置:网站首页>Classes and objects - initialization and cleanup of objects
Classes and objects - initialization and cleanup of objects
2022-06-13 09:26:00 【Hezeze】
.1 Constructors and destructors
If it is not realized artificially , The compiler will implement it automatically, but the function is empty
Constructors : When creating an object, assign a value to the member property of the object Class name (){}
- no return value
- There can be parameters , Can overload
- The system calls automatically , You don't have to call it manually , And only called once
Destructor : Clean up before object destruction ~ Class name (){}
- no return value
- No parameters are allowed , Can't overload
- The system calls automatically , You don't have to call it manually , And only called once
.2 Constructor classification and call
Classification by parameters No arguments structure ( Default structure ) And parametric construction
By type Ordinary constructors and copy constructors
class test {
public:
// No arguments structure
test() {
cout <<"test The parameterless constructor of "<<endl;
}
// There are parametric structures
test(int a) {
cout <<"test The parameterized constructor of "<<endl;
}
// Copy structure
test(const test &p){
// take p Copy the member properties of to the current object
cout <<"test Copy constructor call for "<<endl;
}
};
call :
- Bracket method :
test p1; //**
test p2(10);
test p3(p2);
Be careful : Do not add... When calling the default constructor (). Because the compiler will think that this is a function declaration
- Display method :
test p1;
test p2=test(10);
test p3=test(p2);
Appearing alone test(10);
be called Anonymous object characteristic : End of execution of current line , The system immediately recycles anonymous objects
Be careful : Do not use copy constructors Initialize anonymous objects . Because the compiler will think that redefining object declarations test(p3);
×
- Implicit transformation :
test p2=10; // There are parametric structures
test p3=p2; // Copy structure
.3 When to call the copy constructor
- Initialize another with an already created object
Person p1;
Person p2(p1);
- The method of passing values to function parameters
void dotest(Person p) {
// Call the copy constructor inside this function , It's equivalent to a copy
// Does not change outside the function p Of Member attribute
}
void test() {
Person p;
dotest(p);
}
- Return local object by value
Person dotest2() {
Person p1;
return p1; // Return according to p1 Create a new object
}
.4 Constructor call rules
By default , The compiler provides
- Default constructor ( No arguments , Function body empty )
- Default destructor ( No arguments , Function body empty )
- Default copy constructor , Copy values only for attributes
- Assignment operator operator= Copy the attribute ( see .5 Assignment operator overload )
If you define a parameter constructor , The compiler no longer provides ① Default structure , But provide copy construction
If you define a copy structure , The compiler no longer provides other constructors
.5 Deep copy and shallow copy
Shallow copy : Simple assignment , Copy constructor implemented automatically by compiler
Deep copy : Re apply for a piece of space in the stacking area , Perform copy construction
Shallow copy will cause repeated heap memory release , Because it's just assignment
#include <iostream>
using namespace std; class Per {
public: Per() {
cout << "Pe The default constructor for calls " << endl;
}
Per(int age, int height) {
m_age = age;
m_height = new int(height);
cout << "Pe The parameterized constructor of " << endl;
}
Per(const Per& p) {
cout << "Pe Copy constructor call for " << endl;
m_age = p.m_age;
//m_height=p.m_height; The compiler implements this line of code by default Shallow copy
m_height = new int(*p.m_height); // Deep copy Open up another area in the stack area
}
~Per() {
// When there is memory in the heap , You need to free memory in the destructor if (m_height != NULL) {
delete m_height; // Free up the space opened by the pointer
}
cout << "Pe Destructor call for " << endl;
}
int m_age;
int* m_height; // The pointer opens up a new space in the heap
}; void test1() {
Per p1(12, 150); // The destructor releases for the first time p1 The pointer to m_height Memory space pointed to
Per p2(p1); // The destructor releases again p2 The pointer to the memory space , Repeat release
}
int main() {
test1();
system("pause");
return 0;
}
.6 Initialization list
grammar : Constructors (): attribute 1( value 1), attribute ( value 2){}
class Per {
public: Per(int a,int b,int c):m_a(a),m_b(b),m_c(c){
} // Initialization list
private:
int m_a;
int m_b;
int m_c;
};
When initialization is required Per(10,20,30); that will do
.7 Class object as a member property
Object members : A member of a class is an object of another class
When other class objects are members of this class , First construct class objects , In constructing itself , The order of deconstruction is opposite
class pen {
public: pen(string name) {
m_pname = name;
cout << "pen Constructor call for " << endl;
}
string m_pname;
}; class Person {
public: //m_pen (name) It is equivalent to using implicit transformation method Pen m_pname=name Person (int sex,string name) :m_sex(sex),m_pen(name) // Initialization list
{
cout << "person Constructor call for " << endl;
}
pen m_pen; // Pen name
int m_sex; // Gender
};
.8 Static members
Static member variable :
- All objects share the same data , Point to the same data
- Allocate memory during compilation
- Declaration within class , Class initialization
data type Class name :: Member variable name =
class Person {
public:
static int m_sex; // Gender
};
int Person::m_sex = 1; // Class initialization
void test1() {
// Access to static members
//1, Object access
//Person p
//cout <<p.m_sex<<endl;
//2. Access by class name
cout << Person::m_sex << endl; // However, the private permission cannot be accessed through the class name
}
Static member functions :
- All objects share the same function
- Static member functions can only access static member variables
- Static member functions cannot be accessed outside the private permission class , Can only be accessed through objects
class Person {
public:
static void fun() {
m_sex = 1; // You can access static member variables
//b = 20; // Cannot access non static , It is impossible to distinguish which object's member variable is
}
static int m_sex; // Gender
int b;
};
int Person::m_sex = 1; // Class initialization
边栏推荐
- JUC 原子累加器
- Class loading overview
- LeetCode 6096. Success logarithm of spells and potions (binary search)
- Immutability of shared model
- Simple implementation of database link pool
- 1-4 message passing interface [CSP authentication]
- C language: five custom types
- JUC原子引用与ABA问题
- 【pytorch环境安装搭建】
- (Dijkstra + shortest circuit + by point n^2) acwing 849 Dijkstra finding the shortest path I
猜你喜欢
turtle库的使用数字时钟模拟时钟动态显示
C language: deep understanding of character functions and string functions (1)
Simulink variant model and variant subsystem usage
Yolov5 face learning notes
20220606 Young's inequality for Matrices
C/S模型与P2P模型
Cisco, Huawei network equipment
IP address introduction
Use typescript to complete simple snake eating function
C language: recursive function to realize Hanoi Tower
随机推荐
LeetCode 剑指 Offer 30. 包含min函数的栈
Alibaba senior experts analyze the standard design of protocol
C language: timer principle
A static variable is associated with a class and can be used as long as the class is in memory (the variable does not exist as long as your application terminates). (heap body, stack reference)
计算两个时间相差的天数(支持跨月、跨年)
CAS NO lock
JUC field Updater
JS【中高级】部分的知识点我帮你们总结好了
C language: deep understanding of character functions and string functions (1)
(topological sorting +bfs) acwing 848 Topological sequence of digraph
20211028 adjustment and tracking
谨记! 写代码别太自信! 一定要写点关键日志info输出,不然问题都定位不到。
JUC原子整数
20220606 Young's inequality for Matrices
(Dijkstra + shortest circuit + by point n^2) acwing 849 Dijkstra finding the shortest path I
(dfs+ tree DP) acwing 846 Center of gravity of tree
20211115 any n-order square matrix is similar to triangular matrix (upper triangle or lower triangle)
Remember! Don't be too confident in writing code! Be sure to write some key log info output, or the problem will not be located.
Immutability of shared model
LeetCode 6097. Match after replacing characters (Dictionary)