当前位置:网站首页>Constructors and Destructors
Constructors and Destructors
2022-06-26 16:35:00 【Meaauf】
Constructors
C++ The purpose of is to use classes like standard types , But the above does not make good use of class objects
struct Student()
{
string name;
int age;
};
Student s={
"Mike",19}; // You can easily initialize values using structs
In the structure , It is very convenient to initialize structure members , But class can't , Because the access state of the data part of the class is private , This means that programs cannot access data members directly ;C++ Provides us with a constructor , It is convenient for us to initialize the object when we create it .
class Student
{
public:
Student // Define the constructor Consistent with the class name
{
cout << " The constructor is called " << endl;
}
}
The original intention of constructor is to give initial values to class members ; So we can assign parameters to class members in the constructor , When defining class member names , The parameter name should not be the same as the class member name , A common practice is to use... In data member names m_ Prefixes or suffixes in member names _
class Student
{
private:
string m_name;
public:
Student(string name) // Pass parameters
{
m_name=name; // See passing parameter values to class members
cout << " The constructor is called --" << m_name << endl;
}
}
C++ Provides two ways to initialize objects using constructors , Show calls and implicit calls ; Both methods of invocation are equivalent , Implicit calls are more compact and concise
Student s1=Student("Mike"); // Display call
Student s2("John"); // Implicit call
Constructors are used differently from other class methods , We can call methods through objects , But you can't call a constructor through an object , Before the constructor builds the object , The object does not exist . in other words : Constructors are used to create objects and cannot be called through objects .
Default constructor
The default constructor is when the display initial value is not provided , The constructor used to create the object ; If no constructor is defined in the class , The compiler will provide a default constructor ; If the code writes a constructor , The compiler will use the constructor written by the user
// If you write a constructor But no parameters are provided
public:
Student(string name)
{
cout << name << endl;
}
Student s; // [Error] no matching function for call to 'Student::Student()'
If you want to define a default constructor , We provide default initial values for constructor parameters or use function overloading ; Because there can only be one default constructor , So try not to use both methods at the same time . When initializing all objects , You should ensure that all members have a known and reasonable value
// Method 1: Provide default values
public:
Student(string name="Mike")
{
cout << name << endl;
}
// Method 2: function overloading
Student()
{
;
}
When using to create a parameterless constructor, you should pay attention to , Avoid using parentheses to create objects when instantiating objects
Student()
{
cout << " The constructor is called " << endl;
}
// Instantiate objects
Student s; // " The constructor is called "
Student s(); // No output value
But use Student s() when , The compiler will think that you are main Function declares a function , The return value is Student Function of
Destructor
After the constructor creates the object , When the program expires , The destructor is automatically called . In practical use , If the constructor uses new Allocated memory , Then the destructor can use delete Free memory . Same as constructor , Destructors can have no return value and no declared type ; The difference is : Destructor has no arguments .
// Define a base destructor
class Student
{
public:
~Student()
{
cout << "Bye." << endl;
}
}
The compiler will decide when to call the destructor
- If you create a static storage class object , Destructors are automatically called at the end of the program ;
- If you create an automatic storage class object , The destructor will be called automatically after the program executes the code block ;
- If you use new establish , Will be stored on the stack , When using delete After releasing memory , The destructor will automatically call
After the class object expires , The destructor will automatically call , So there must be a destructor , If the program does not write a destructor , The compiler will implicitly declare a default destructor , After the object is deleted , Provide default destructors
Anonymous object
Anonymous objects are characterized by : After the execution of the current statement , The anonymous object will be destroyed immediately
class Student // Defining classes
{
public:
Student()
{
cout << " The constructor is called " << endl;
}
~Student()
{
cout << " Destructor called " << endl;
}
};
Student(); // Create anonymous objects
cout << "Bye." << endl;
Common object

Anonymous object

边栏推荐
- 心情不好,我就这样写代码
- I regard it as a dry product with a monthly income of more than 30000 yuan for sidelines and more than 10000 yuan for novices!
- Cloud platform monitoring system based on stm32+ Huawei cloud IOT design
- Keepalived 实现 Redis AutoFailover (RedisHA)
- Scala Foundation (2): variables et types de données
- Redis顺序排序命令
- Kept to implement redis autofailover (redisha) 1
- How can I get the stock account opening discount link? Is online account opening safe?
- R language uses cor function to calculate the correlation matrix for correlation analysis, uses corrgram package to visualize the correlation matrix, reorders rows and columns using principal componen
- How to separate jar packages and resource files according to packaging?
猜你喜欢

C语言所有知识点小结

Cloud platform monitoring system based on stm32+ Huawei cloud IOT design

Arduino uno + DS1302 simple time acquisition and serial port printing

Science | 红树林中发现的巨型细菌挑战传统无核膜观念

Knowing these commands allows you to master shell's own tools

TCP congestion control details | 1 summary

IAR engineering adapts gd32 chip

清华“神奇药水”登Nature:逆转干细胞分化,比诺奖成果更进一步,网友:不靠精子卵子就能创造生命了?!...

Oilfield exploration problems

What does the inner structure of the neural network "alchemy furnace" look like? An interpretation of the thesis by the doctor of Oxford University
随机推荐
[from deleting the database to running] the end of MySQL Foundation (the first step is to run.)
基于STM32+华为云IOT设计的云平台监控系统
JS tutorial electron JS is a good tool for designing powerful multi platform desktop applications
Net based on girdview control to delete and edit row data
Lifeifei's team applied vit to the robot, increased the maximum speed of planning reasoning by 512 times, and also cued hekaiming's Mae
108. 简易聊天室11:实现客户端群聊
对话长安马自达高层,全新产品将在Q4发布,空间与智能领跑日系
【力扣刷题】11.盛最多水的容器//42.接雨水
Développer un opérateur basé sur kubebuilder (démarrer)
JS tutorial using electron JS build native desktop application ping pong game
Niuke Xiaobai monthly race 50
[从零开始学习FPGA编程-46]:视野篇 - 集成电路的发展与技术进步
安信证券排名第几位?开户安全吗?
[time complexity and space complexity]
I regard it as a dry product with a monthly income of more than 30000 yuan for sidelines and more than 10000 yuan for novices!
Hyperf框架使用阿里云OSS上传失败
Scala 基礎 (二):變量和數據類型
【力扣刷题】二分查找:4. 寻找两个正序数组的中位数
Least squares system identification class II: recursive least squares
并发编程整体脉络