默认情况下,c++编译器至少给一个类添加3个函数
1.默认构造函数(无参,函数体为空)
2.默认析构函数(无参,函数体为空)
3.默认拷贝构造函数,对属性进行值拷贝(“=”号赋值)
构造函数调用规则如下:
如果用户定义了有参构造函数,c++不再提供默认无参构造,但是会提供默认拷贝构造
如果用户定义了拷贝构造函数,c++不会再提供其他构造函数
#include<iostream>
using namespace std;
//构造函数的调用规则
//1.创建一个类,C++编译器会给每个类都添加至少三个函数
//默认构造(空实现)
//析构函数(空实现)
//拷贝函数(值拷贝)
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 test1()
{
Person p;
p.m_Age = 18;
Person p2(p);
cout << "p2的年龄为:" <<p2.m_Age<< endl;
}
int main()
{
test1();
return 0;
}
out:
Person的默认构造函数调用
Person的拷贝构造函数调用
p2的年龄为:18
Person的析构函数调用
Person的析构函数调用
若将拷贝函数注释,则得到以下结果:
out:
Person的默认构造函数调用
p2的年龄为:18
Person的析构函数调用
Person的析构函数调用
编译器自动提供的拷贝构造函数会执行以下代码,做一个值拷贝操作,即:
m_Age = p.m_Age;
将p的所有属性做一个等号赋值的操作。所有打印的p2年龄为18
#include<iostream>
using namespace std;
//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 test2()
{
Person p(20);
Person p2(p);
cout << "p2的年龄为:" << p2.m_Age << endl;
}
int main()
{
test2();
return 0;
}
out:
Person的有参构造函数调用
p2的年龄为:20
Person的析构函数调用
Person的析构函数调用
总结:默认-->有参-->拷贝,一个比一个高级,定义了其中一个,编译器则不提供之前的