侯捷老师-P12虚函数与多肽-继承时子类有复合类
在P12课时,侯捷老师留了课外思考题
问:继承时子类有复合类,构造函数应该是先调用父类的,还是复合类的
答:先父类,再复合类
代码实现如下:
#include<iostream> using namespace std; class Base{ public: Base() { cout<<"base"<<endl; }; }; class Component{ public: Component() { cout<<"conponent"<<endl; }; }; class Derived : public Base{ public: Derived(){ } Component C; }; int main() { Derived D; return 0; }
输出为:
base
conponent