简体   繁体   English

c++ [钻石配置] 如何用继承初始化?

[英]c++ [diamond configuration] How to initialize with inheritance?

I apologize if my question is dumb but i'm a beginner in c++.如果我的问题很愚蠢,我深表歉意,但我是 C++ 的初学者。 I'm working on diamond inheritance and i would like to know if it is possible to choose the specific parent class which will initilize an attribute for the child class.我正在研究钻石继承,我想知道是否可以选择特定的父类来初始化子类的属性。

To sum up, i would like this code to output B总而言之,我希望这段代码输出B

Thank you for your answers !谢谢您的回答 !

PS: i'm working with c++98 PS:我正在使用 c++98

#include <iostream>

class A
{
    protected:
        char    m_char;
    public:
        A(): m_char('A'){};
        char    getChar(){return m_char;};
        ~A(){};
};

class B : virtual public A
{
    private:
        
    public:
        B() {m_char = 'B';};
        ~B(){};
};

class C : virtual public A
{
    private:
        
    public:
        C() {m_char = 'C';};
        ~C(){};
};

class D : public B, public C
{
    private:
        
    public:
        D() {m_char = B::m_char;};
        ~D(){};
};

int main(void)
{
    D   d;
    std::cout << d.getChar() << std::endl;
}

Virtual base classes are initialized In depth-first, left-to-right order.虚拟基类以深度优先、从左到右的顺序进行初始化。 So you would need to name B second in your inheritance for D to call its constructor last and thus setting the variable to B at the end.因此,您需要在继承中将 B 命名为第二个,以便 D 最后调用其构造函数,从而在最后将变量设置为 B。


class D : public C, public B

m_char = B::m_char; is self assignment (there is only one m_char ).是自赋值(只有一个m_char )。

In virtual inheritance, it is the most derived class which initialize the virtual class (body does assignment).在虚拟继承中,初始化虚拟类的是派生最多的类(主体进行赋值)。

How about being explicit in construction:如何在构造中明确:

#include <iostream>

class A
{
protected:
    char m_char;
public:
    A() : m_char('A') {}
    char getChar() const { return m_char; }
    virtual ~A() {}
};

class B : virtual public A
{
public:
    B() : A('B') {}
};

class C : virtual public A
{
public:
    C() : A('C') {}
};

class D : public B, public C
{
public:
    D() : A('B'), B(), C() {}
};

int main()
{
    D d;
    std::cout << d.getChar() << std::endl;
}

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

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