原来碰到的一道面试,大概是这样子B是A的子类,B里面还有一个C类的成员对象,问A,B,C构造函数的调用次序。很简单的一道题目,然而却有点懵逼,主要纠结A和C的构造函数哪个先调用?今天写代码测试了一下。
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "this is Base....." << endl; }
};
class Member {
public:
Member() { cout << "this is Member....." << endl; }
};
class Derive:public Base {
public:
Derive() { cout << "this is Derive....." << endl; }
private:
Member m;
};
int main() {
Derive d;
return 0;
}
最终调用结果如下:父类构造函数(A)先调用,其次成员构造函数(C),子类构造函数(B)最后调用;
win10下VS2015输出:
Ubuntu16.04下g++输出
结果一致。