内容来自小破站《黑马程序员C++》复习自用
【学习笔记】C++ 核心编程(五)类和对象——构造函数的调用规则
4.2 对象的初始化和清理
4.2.4 构造函数调用规则
默认情况下,C++编译器至少给一个类添加3个函数
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
构造函数调用规则如下:
- 如果用户定义有参构造函数,C++不在提供默认无参构造,但是会提供默认拷贝构造函数
- 如果用户定义拷贝构造函数,C++不会再提供其他构造函数
#include <iostream>
using namespace std;
//默认情况下,C++编译器至少给一个类添加3个函数
//1.默认构造函数(无参,函数体为空)
//2.默认析构函数(无参,函数体为空)
//3.默认拷贝构造函数,对属性进行值拷贝
class Person
{
public:
Person() //默认构造函数
{
cout<<"Person的默认构造函数调用" << endl;
}
Person(int age)//有参构造函数
{
cout << "Person的有参构造函数调用" << endl;
m_Age = age;
}
Person(const Person& p)//拷贝构造函数
{
cout << "Person的拷贝构造函数调用" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
int m_Age;
};
void test01()
{
Person p;
p.m_Age = 18;
Person p2(p);
cout << "The age of p2 is " << p2.m_Age << endl;
}
int main() {
test01();
system("pause");
return 0;
}
但是假设,没有写p2拷贝构造函数,那么p2是多少?
如果我们写了有参构造函数,编译器就不再提供默认构造,但是会提供默认拷贝构造函数
#include <iostream>
using namespace std;
//一、默认情况下,C++编译器至少给一个类添加3个函数
//1.默认构造函数(无参,函数体为空)
//2.默认析构函数(无参,函数体为空)
//3.默认拷贝构造函数,对属性进行值拷贝
//二、如果我们写了有参构造函数,编译器就不再提供默认构造,但是会提供默认拷贝构造函数
class Person
{
public:
Person()
{
cout<<"Person的默认构造函数调用" << endl;
}
Person(int age)//有参构造函数
{
cout << "Person的有参构造函数调用" << endl;
m_Age = age;
}
Person(const Person& p)//拷贝构造函数
{
cout << "Person的拷贝构造函数调用" << endl;
m_Age = p.m_Age; //这里会默认生成,做一个值拷贝
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
int m_Age;
};
//void test01()
//{
// person p;
// p.m_age = 18;
// person p2(p);
// cout << "the age of p2 is " << p2.m_Age << endl;
//}
void test02()
{
Person p(28);
Person p2(p);
cout << "the age of p2 is " << p2.m_Age << endl;
}
int main() {
test02();
system("pause");
return 0;
}
小结: