[英]Use of virtual inheritance outside diamond inheritance problem to allow leapfrogging
Consider the following program:考虑以下程序:
#include <iostream>
#include <string>
class B
{
public:
int n;
B() : n(0) {}
B(int m) : n(m) {}
};
class D1 : virtual public B
{
public:
int a;
D1() : a(0) {}
D1(int m) : a(m) {}
};
class D2 : public D1
{
public:
int d;
D2() : d(0) {}
D2(int m) : d(m) {}
D2(int j, int k) : d(j), D1(k) {}
D2(int i, int j, int k) : d(i), D1(j), B(k) {} //Without virtual inheritance,
//must add new constructor to D1.
};
int main()
{
std::string s;
D2 d2(0, 1, 2);
std::cout << "d2.n = " << d2.n << "\n";
std::cout << "d2.a = " << d2.a << "\n";
std::cout << "d2.d = " << d2.d << "\n";
std::cout << "Press ENTER to exit.\n";
getline(std::cin, s);
}
Having D1 inherit virtually from B allows me to call the constructor of B from the constructor of D2, leapfrogging over the class D1.让 D1 实际上继承自 B 允许我从 D2 的构造函数调用 B 的构造函数,跳过 class D1。
Can this use of virtual inheritance apart from the diamond-inheritance problem cause undefined behavior or other harm?除了钻石继承问题之外,虚拟 inheritance 的这种使用是否会导致未定义的行为或其他危害?
I have never seen virtual inheritance used except to solve the diamond inheritance problem.除了解决钻石inheritance问题外,我从未见过使用虚拟inheritance。
Can this use of virtual inheritance apart from the diamond-inheritance problem cause undefined behavior or other harm?
除了钻石继承问题之外,虚拟 inheritance 的这种使用是否会导致未定义的行为或其他危害?
Virtual inheritance, for any purposes, incurs these "harms":虚拟 inheritance,出于任何目的,都会招致这些“危害”:
dynamic_cast
.dynamic_cast
完成。 The faster static_cast
is not possible.static_cast
是不可能的。 Your example doesn't introduce any Undefined Behavior or harm that don't exist for any other usage of virtual inheritance.您的示例不会引入任何其他虚拟 inheritance 不存在的未定义行为或危害。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.