面试题答案
一键面试1. 派生类调用基类不同构造函数的方式
在C++ 中,派生类通过在其构造函数的初始化列表中调用基类的构造函数来合理调用基类不同构造函数。例如:
#include <iostream>
// 基类
class Base {
public:
// 基类的第一个构造函数
Base() {
std::cout << "Base default constructor called." << std::endl;
}
// 基类的第二个构造函数
Base(int num) {
std::cout << "Base constructor with int parameter called, num = " << num << std::endl;
}
};
// 派生类
class Derived : public Base {
public:
// 派生类构造函数,调用基类默认构造函数
Derived() : Base() {
std::cout << "Derived default constructor called." << std::endl;
}
// 派生类构造函数,调用基类带int参数的构造函数
Derived(int num) : Base(num) {
std::cout << "Derived constructor with int parameter called." << std::endl;
}
};
在上述代码中,Derived
类的两个构造函数分别通过初始化列表调用了 Base
类的不同构造函数。
2. 构造函数执行顺序
当创建一个派生类对象时,构造函数的执行顺序是:
- 首先调用基类的构造函数。
- 然后调用派生类的构造函数。
例如,当执行 Derived d(5);
时,输出为:
Base constructor with int parameter called, num = 5
Derived constructor with int parameter called.
3. 原理
- 因为派生类对象包含基类对象作为其一部分(继承关系),在创建派生类对象时,必须先创建其基类部分。所以基类构造函数先执行,为派生类对象中的基类部分进行初始化。
- 然后执行派生类的构造函数,对派生类特有的成员进行初始化。