首先要了解派生类调用构造函数过程:基类构造函数–>派生类构造函数
1.基类有默认构造函数,派生类未显示调用时,派生类自动调用基类的默认构造函数;
#include <iostream>using namespace std;class Father{public:Father(){cout << "基类默认构造函数!\n";}};class Children : public Father{public:Children(){cout << "派生类构造函数!\n" << endl;}};int main(int argc, char** argv){Children rec;return 0;}
2.基类有默认构造函数,派生类显示调用时,派生类自动调用基类的默认构造函数;
#include <iostream>using namespace std;class Father{public:Father(){cout << "基类默认构造函数!\n";}};class Children : public Father{public:Children() : Father(){cout << "派生类构造函数!\n" << endl;}};int main(int argc, char** argv){Children rec;return 0;}
3.基类没有默认构造函数,派生类显示调用时,派生类会调用系统为基类生成的默认构造函数;
#include <iostream>using namespace std;class Father{public:// Father()// {// cout << "基类默认构造函数!\n";// }};class Children : public Father{public:Children() : Father(){cout << "派生类构造函数!\n" << endl;}};int main(int argc, char** argv){Children rec;return 0;}
4.基类没有默认构造函数,派生类未显示调用时,派生类会调用系统为基类生成的默认构造函数;
#include <iostream>using namespace std;class Father{public:// Father()// {// cout << "基类默认构造函数!\n";// }};class Children : public Father{public:Children()// : Father(){cout << "派生类构造函数!\n" << endl;}};int main(int argc, char** argv){Children rec;return 0;}
5.基类有带参数的构造函数,也有默认构造函数,派生类未显示调用基类构造函数时,派生类会调用基类默认构造函数;
#includeusing namespace std;class Father{public:Father(){cout << “基类默认构造函数!\\n”;}Father(int nNum){cout << “基类传参构造函数!\\n”;}};class Children : public Father{public:Children(){cout << “派生类构造函数!\\n” << endl;}};int main(int argc, char\*\* argv){Children rec;return 0;
}
6.基类有带参数的构造函数,也有默认构造函数,派生类显示调用基类一种构造函数时,派生类会调用基类该种构造函数;
#include <iostream>using namespace std;class Father{public:Father(){cout << "基类默认构造函数!\n";}Father(int nNum){cout << "基类传参构造函数!\n";}};class Children : public Father{public:Children() : Father(1){cout << "派生类构造函数!\n" << endl;}};int main(int argc, char** argv){Children rec;return 0;}
错误方式:
基类仅写了带参数的构造函数,没写不带参数的默认构造函数时,而派生类又没有显示调用基类构造函数时,编译失败。因为基类写了构造函数,系统就不会为基类生成默认构造函数,派生类想调用基类的默认构造函数时找不到;
#include <iostream>using namespace std;class Father{public:// Father()// {// cout << "基类默认构造函数!\n";// }Father(int nNum){cout << "基类传参构造函数!\n";}};class Children : public Father{public:Children()// : Father(){cout << "派生类构造函数!\n" << endl;}};int main(int argc, char** argv){Children rec;return 0;}
如果觉得派生类调用基类构造函数情况太多,不好记忆,那么每次写派生类构造函数时最好显示调用基类构造函数!
