默认情况下,c++编译器至少给一个类添加三个函数
默认构造函数(无参 函数体为空)
默认析构函数(无参,函数体为空)
默认拷贝构造函数,对属性惊醒值拷贝
构造函数调用规则如下:
如果用户定义有参构造函数 c++不在提供默认无参构造,但是会提供默认拷贝构造
如果用户定义拷贝构造函数,c++不在提供其他构造函数
//4.2.4 构造函数调用规则
#include<iostream>
using namespace std;
//1、创建一个类 编译器给每个类添加至少3个函数
//默认构造(空实现)
//析构函数(空实现)
//拷贝构造(值拷贝)
//2、如果我们写了有参构造参数,编译器就不再提供默认构造,但是依然提供拷贝构造函数
//如果我们写了拷贝构造函数,编译器就不再提供其他普通构造函数
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 = 19;
Person p2(p);
cout << "p2的年龄为:" << p2.m_Age << endl;
}
void test02()
{
Person p(18);
Person p2(p);
cout << "p2的年龄为:" << p2.m_Age << endl;
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
本文介绍了C++中构造函数、析构函数和拷贝构造函数的默认行为以及用户自定义这些函数时的规则。当用户定义了有参构造函数,编译器不再提供默认无参构造函数,但仍然提供拷贝构造函数。而自定义拷贝构造函数则会导致编译器不再提供其他普通构造函数。通过示例代码展示了这些规则的运用。

被折叠的 条评论
为什么被折叠?



