面试题答案
一键面试在C++中,虚基类构造参数传递常见方式有以下两种:
1. 在直接派生类的构造函数初始化列表中传递
当存在虚继承关系时,最底层的派生类负责初始化虚基类。例如:
#include <iostream>
class A {
public:
A(int a) : m_a(a) {
std::cout << "A constructor with a = " << m_a << std::endl;
}
private:
int m_a;
};
class B : virtual public A {
public:
B(int a, int b) : A(a), m_b(b) {
std::cout << "B constructor with b = " << m_b << std::endl;
}
private:
int m_b;
};
class C : virtual public A {
public:
C(int a, int c) : A(a), m_c(c) {
std::cout << "C constructor with c = " << m_c << std::endl;
}
private:
int m_c;
};
class D : public B, public C {
public:
D(int a, int b, int c) : A(a), B(a, b), C(a, c) {
std::cout << "D constructor" << std::endl;
}
};
在上述代码中,D
类作为最底层的派生类,通过其构造函数初始化列表同时初始化虚基类A
,以及直接基类B
和C
。
2. 通过中间派生类间接传递
在某些情况下,中间派生类也可以帮助传递虚基类构造参数。例如:
#include <iostream>
class X {
public:
X(int x) : m_x(x) {
std::cout << "X constructor with x = " << m_x << std::endl;
}
private:
int m_x;
};
class Y : virtual public X {
public:
Y(int x, int y) : X(x), m_y(y) {
std::cout << "Y constructor with y = " << m_y << std::endl;
}
protected:
int m_y;
};
class Z : public Y {
public:
Z(int x, int y, int z) : Y(x, y), m_z(z) {
std::cout << "Z constructor with z = " << m_z << std::endl;
}
private:
int m_z;
};
这里Z
类通过Y
类间接传递参数给虚基类X
。Y
类在其构造函数初始化列表中初始化虚基类X
,Z
类在初始化列表中初始化Y
类,从而间接完成对虚基类X
的初始化。