简体   繁体   English

使用virtual inheritance outside diamond inheritance问题允许越级

[英]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,出于任何目的,都会招致这些“危害”:

  • Access to the virtual base class is via pointer, which is potentially slower访问虚拟基址 class 是通过指针,这可能会更慢
  • Every derived class, at all depths, must be responsible for constructing the virtual base每个派生class,在所有深度,都要负责构建虚拟基地
  • Downcasting from the virtual base must be done via 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM