C++的编译器在某些特定的情况下,会给类自动生成无参的构造函数,比如:
(1) 成员变量在声明的同时进行了初始化
#include <iostream>
using namespace std;
class Person {
public:
int m_age = 5;
};
int main() {
Person person;
getchar();
return 0;
}
(2) 有定义虚函数
#include <iostream>
using namespace std;
class Person {
public:
int m_age;
virtual void run() {
}
};
int main() {
Person person;
getchar();
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;
getchar();
return 0;
}
(4) 包含了对象类型的成员,且这个成员有构造函数(编译器生成或自定义)
#include <iostream>
using namespace std;
class Car {
public:
int m_price;
Car() {}
};
class Person {
public:
Car car;
};
int main() {
Person person;
getchar();
return 0;
}
(5) 父类有构造函数(编译器生成或自定义)
#include <iostream>
using namespace std;
class Person {
public:
Person() {}
};
class Student : public Person {
public:
};
int main() {
Student student;
getchar();
return 0;
}
总结:对象创建后,需要做一些额外操作时(比如内存操作、函数调用),编译器一般都会为其自动生成无参的构造函数。