面试题答案
一键面试- 初始化原则:
- 基类的
const
成员和引用成员必须在基类的构造函数初始化列表中初始化。 - 派生类构造函数在初始化列表中首先调用基类构造函数来初始化基类部分,然后初始化自身新增的成员。
- 中间层派生类在初始化列表中先调用基类构造函数,再对需要特殊初始化的成员进行初始化。
- 最底层派生类在初始化列表中先调用中间层派生类构造函数,再初始化自身新成员。
- 基类的
- 代码实现:
#include <iostream>
class Base {
public:
const int constValue;
int& refValue;
Base(int value, int& ref) : constValue(value), refValue(ref) {
std::cout << "Base constructor" << std::endl;
}
};
class Middle : public Base {
public:
int specialValue;
Middle(int value, int& ref, int special) : Base(value, ref), specialValue(special) {
std::cout << "Middle constructor" << std::endl;
}
};
class Bottom : public Middle {
public:
int newMember;
Bottom(int value, int& ref, int special, int newVal) : Middle(value, ref, special), newMember(newVal) {
std::cout << "Bottom constructor" << std::endl;
}
};
你可以这样使用这些类:
int main() {
int num = 10;
Bottom bottom(5, num, 20, 30);
return 0;
}
在上述代码中:
Base
类有const
成员constValue
和引用成员refValue
,在其构造函数初始化列表中完成初始化。Middle
类派生自Base
,在其构造函数初始化列表中先调用Base
的构造函数,再初始化自身的specialValue
。Bottom
类派生自Middle
,在其构造函数初始化列表中先调用Middle
的构造函数,再初始化自身的newMember
。