一个广为流传的、很多教程/书籍都推崇的错误结论:默认情况下,编译器会为每一个类生成空的无参的构造函数。
在下面代码中,编译器并没有生成一个空的无参的构造函数,而是直接给成员变量赋值。
#include <iostream>
using namespace std;
class Person
{
public:
int m_age;
};
int main()
{
Person person;
person.m_age = 10;
return 0;
}
正确理解:在某些特定的情况下,编译器才会给类自动生成空的无参的构造函数。
(1) 成员变量在声明的同时进行了初始化。
#include <iostream>
using namespace std;
class Person
{
public:
int m_age = 0;
};
int main()
{
Person person;
person.m_age = 10;
return 0;
}
(2) 有定义虚函数。
#include <iostream>
using namespace std;
class Person
{
public:
int m_age;
virtual void run()
{
}
};
int main()
{
Person person;
return 0;
}
(3) 虚继承了其他类。
#include <iostream>
using namespace std;
class Person
{
public:
int m_age;
void run()
{
}
};
class Student : virtual public Person
{
public:
int m_score;
};
int main()
{
Student student;
return 0;
}
(4) 包含了对象类型的成员且这个成员有构造函数(编译器生成或自定义)。
#include <iostream>
using namespace std;
class Car
{
public:
int m_price;
Car() {}
};
class Person
{
public:
Car car;
};
int main()
{
Person person;
return 0;
}
(5) 父类有构造函数(编译器生成或自定义)。
#include <iostream>
using namespace std;
class Person
{
public:
int m_age;
Person() {}
};
class Student : public Person
{
public:
int m_score;
};
int main()
{
Student student;
return 0;
}
总结:对象创建后,需要做一些额外操作时,比如内存操作、函数调用等,编译器一般都会为其自动生成无参的构造函数。