当前位置:网站首页>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

边栏推荐
- IAR engineering adapts gd32 chip
- Cloud platform monitoring system based on stm32+ Huawei cloud IOT design
- 板卡的分级调试经验
- Codeforces Round #802 (Div. 2)
- JS tutorial electron JS is a good tool for designing powerful multi platform desktop applications
- C语言所有知识点小结
- 最小二乘系统辨识课 中篇:递归最小二乘
- 精致妆容成露营“软实力”,唯品会户外美妆护肤产品销量激增
- Scala 基礎 (二):變量和數據類型
- Redis migration (recommended operation process) 1
猜你喜欢
Redis Guide (8): principle and implementation of Qianfan Jingfa distributed lock

5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?

若依如何实现接口限流?

神经网络“炼丹炉”内部构造长啥样?牛津大学博士小姐姐用论文解读

Ideal path problem

Research on natural transition dubbing processing scheme based on MATLAB

Pybullet robot simulation environment construction 5 Robot pose visualization
![[understanding of opportunity -31]: Guiguzi - Daoyu [x ī] Crisis is the coexistence of danger and opportunity](/img/e8/9c5f1658a252c3c80503b5021917f6.jpg)
[understanding of opportunity -31]: Guiguzi - Daoyu [x ī] Crisis is the coexistence of danger and opportunity

当一个程序员一天被打扰 10 次,后果很惊人!

基于Kubebuilder开发Operator(入门使用)
随机推荐
STM32F103C8T6实现呼吸灯代码
JS tutorial using electron JS build native desktop application ping pong game
[learn FPGA programming from scratch -46]: Vision - development and technological progress of integrated circuits
神经网络“炼丹炉”内部构造长啥样?牛津大学博士小姐姐用论文解读
Data analysis - numpy quick start
100+数据科学面试问题和答案总结 - 基础知识和数据分析
请指教同花顺软件究竟是什么?网上开户是否安全么?
In a bad mood, I just write code like this
Kept to implement redis autofailover (redisha) 1
Oilfield exploration problems
Binary array command of redis
[understanding of opportunity -31]: Guiguzi - Daoyu [x ī] Crisis is the coexistence of danger and opportunity
Several forms of buffer in circuit
【蓝桥杯集训100题】scratch辨别质数合数 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第15题
The first batch in the industry! Tencent cloud security and privacy computing products based on angel powerfl passed CFCA evaluation
固件供应链公司Binarly获得WestWave Capital和Acrobator Ventures的360万美元投资
[graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap
Redis 迁移(操作流程建议)
Tencent Peking University's sparse large model training acceleration program het was selected into the VLDB of the international summit
若依如何实现接口限流?