从属成员初始化,当重新排序不可能时 [英] Dependent member initialization, when reorder is not possible

查看:133
本文介绍了从属成员初始化,当重新排序不可能时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
class BarParent
{
    public:
        int x;
        virtual void fuz() = 0;
};

class BarChild : public BarParent
{
    public: 
        BarChild(int new_x){x = new_x;}
        virtual void fuz(){}
};

class FooParent
{
    public:
        BarParent* p_barPar;
        FooParent (BarChild* new_p_bar)
        {
            p_barPar = new_p_bar;
            std::cout << p_barPar->x << std::endl;
        }
};

class FooChild: public FooParent
{
    public:
        BarChild barChild;
        FooChild(int new_x):FooParent(&barChild), barChild(new_x){}
};
int main()
{   
    FooChild foo(60);

    BarChild bar(99);
    FooParent fooP(&bar);
}

输出:

-548726160 
99

得到这个结果(未定义的行为), barChild 在被初始化之前使用。

I understand why I am getting this result(undefined behavior), barChild is used before it is initiailized. My question is what is the 'right' to do handle this.

推荐答案

这是设计

根据您自己的设计:


  • A BarChild 必须在 FooParent 之前构建。

  • 必须在 FooChild 之前构建 FooParent

  • 必须在 BarChild 之前构建 FooChild

  • A BarChild must be constructed before FooParent.
  • A FooParent must be constructed before a FooChild.
  • A FooChild must be constructed before a BarChild.

当你想要 FooParent FooChild 来引用同一个Bar对象

When you want both FooParent and FooChild to refer to this same Bar object - as you're attempting in your code - design the parent class to manage it.

一个示例解决方案:

    FooParent (BarChild* new_p_bar)
    {
        if ( new_p_bar == NULL )
           new_p_bar = new BarChild;

        p_barPar = new_p_bar;
        std::cout << p_barPar->x << std::endl;
    }

这里, FooChild 不需要此对象的自己的实例。

Here, FooChild doesn't need its own instance of this object.

这篇关于从属成员初始化,当重新排序不可能时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆