简体   繁体   English

基类的多个虚拟继承和构造函数调用

[英]Multiple virtual inheritance and constructor call of base class

There is this code: 有这个代码:

#include <iostream>

class Bazowa
{
    int x;
public:
    Bazowa() : x(55){}
    Bazowa(int x_) : x(x_) {}
    void fun()
    {
      std::cout << x << "fun\n";
    }
};

class Pochodna1 : virtual public  Bazowa
{
public:
    Pochodna1() : Bazowa(101) {}
};

class Pochodna2 : virtual public  Bazowa
{
public:
    Pochodna2() : Bazowa(103) {}
};

class SuperPochodna : public Pochodna1, public Pochodna2
{
public:
    SuperPochodna() : {}
};


int main() {
    SuperPochodna sp; 
    sp.fun();     // prints 55fun

    return 0;
}

After execution of this program, it will print "55fun". 执行该程序后,将打印“55fun”。 What happened to constructor calls in class Pochodna1 and Pochodna2 - are they ignored? 在Pochodna1和Pochodna2类中构造函数调用发生了什么 - 它们被忽略了吗? Why member 'x' of class Bazowa is set to '55', but not '101' or '103'? 为什么班级Bazowa的成员'x'被设置为'55',而不是'101'或'103'?

Virtual base constructors are always called from the final leaf class. 始终从最终叶类调用虚拟基础构造函数。 None of the other constructors for the virtual base are called. 不会调用虚拟基础的其他构造函数。 In your case SuperPochodna() is calling Bazowa() and the calls to Bazowa(int) in Pochodna1 and Pochodna2 are not used. 在你的情况下, SuperPochodna()调用Bazowa()并且不使用Pochodna1Pochodna2中对Bazowa(int)的调用。

See http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14 or just google "virtual base constructor". 请参阅http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14或只是谷歌“虚拟基础构造函数”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用虚拟继承在模板类中调用基本构造函数 - Unable to call base constructor in template class using virtual inheritance 调用祖父构造函数的虚拟但不是多重继承 - Virtual but not multiple inheritance to call grandparent constructor 具有通用基类的多重虚拟继承 - Multiple virtual inheritance with common base class 从C++中具有多重继承的类派生的类:派生类试图调用根基类构造函数 - Class derived from a class with multiple inheritance in C++: the derived class is trying to call the root base class constructor 多重继承,复制构造函数和基类初始化? - Multiple Inheritance, copy constructor, and base class initialization? 虚拟基类和继承 - Virtual base class and inheritance 虚继承基构造函数消除 - virtual inheritance base constructor elimination 如何在虚拟继承下游使用参数化基类构造函数 - How to use parameterized base class constructor downstream of virtual inheritance 在多级继承的情况下,无法理解虚基类构造函数 - Not able to understand virtual base class constructor in case of multilevel inheritance 使用虚拟继承的类似乎允许基类构造函数覆盖另一个基类的成员 - Class using virtual inheritance seems to allow a base class constructor to overwrite another base class' members
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM