两种分类方式:
按参数分为: 有参构造和无参构造
按类型分为: 普通构造和拷贝构造
三种调用构造函数的方法
- 括号法
- 显式法
- 隐式转换法
#include <bits/stdc++.h>
using namespace std;
class Person{
public:
Person(){
cout << "Person默认构造函数的调用" << endl;
}
Person(int num){ // 有参构造
this->m_Num = num;
cout << "Person有参构造函数的调用" << endl;
}
Person(const Person& per){
this->m_Num = per.m_Num;
cout << "Person拷贝构造函数的调用" << endl;
}
~Person(){
cout << "Person析构函数的调用" << endl;
}
public:
int m_Num;
};
int main(){
Person person1; // 调用无参构造函数
Person person2(10); // 括号法调用有参构造函数
Person person3(person2); // 括号法调用拷贝构造函数
Person person4 = Person(20); // 显式法调用构造函数
Person person5 = 10;
cout << "Person2 = " << person2.m_Num << endl;
cout << "Person3 = " << person3.m_Num << endl;
cout << "Person4 = " << person4.m_Num << endl;
cout << "Person5 = " << person5.m_Num << endl;
return 0;
}