本文介绍了从属成员初始化,当重新排序不可能时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#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 beforeFooParent
. - A
FooParent
must be constructed before aFooChild
. - A
FooChild
must be constructed before aBarChild
.
当你想要 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.
这篇关于从属成员初始化,当重新排序不可能时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!