默认情况下,c++编译器至少给一个类添加3个函数
1、默认构造函数(无参,函数体为空)
2、默认析构函数(无参,函数体为空)
3、默认拷贝构造函数,对属性进行值拷贝
构造函数的调用规则如下:
(1)如果用户定义有参构造函数,c++不在提供默认无参构造,但是会提供默认拷贝构造(
(2)如果用户定义拷贝工造函数,c++不会再提供其他构造函数
// 构造函数的调用规则.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
//构造函数的调用规则
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age)
{
cout << "Person的有参构造函数调用" << endl;
}
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 << "p2的年龄为: " << p2.m_Age << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
此时的输出如下

如果我们把拷贝函数注释掉
此时我们看到p2的值仍然为18,说明类里有一个默认拷贝参数
// 构造函数的调用规则.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
//构造函数的调用规则
class Person
{
public:
//Person()
//
//cout << "Person的默认构造函数调用" << endl;
//}
Person(int age)
{
cout << "Person的有参构造函数调用" << endl;
}
Person(const Person& p)
{
m_Age = p.m_Age;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
int m_Age;
};
void test01()
{
Person p;
p.m_Age = 18;
Person p2(p);
cout << "p2的年龄为: " << p2.m_Age << endl;
}
void test02()
{
Person p;
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
此时会报错,因为当我们定义了一个有参构造函数就不在提供默认构造函数,所以会发生报错
970

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



