MST

星途 面试题库

面试题:C++初始化成员列表在继承体系中的特殊应用场景

在一个具有多层继承关系的C++类体系中,有一个基类含有const成员和引用成员,中间层派生类需要对某些成员进行特殊初始化,最底层派生类又有新的成员需要初始化。请描述如何合理使用初始化成员列表来完成整个继承体系中所有成员的正确初始化,并给出具体代码实现。
49.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 初始化原则
    • 基类的const成员和引用成员必须在基类的构造函数初始化列表中初始化。
    • 派生类构造函数在初始化列表中首先调用基类构造函数来初始化基类部分,然后初始化自身新增的成员。
    • 中间层派生类在初始化列表中先调用基类构造函数,再对需要特殊初始化的成员进行初始化。
    • 最底层派生类在初始化列表中先调用中间层派生类构造函数,再初始化自身新成员。
  2. 代码实现
#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