问题描述
是否在构造函数体之前构造了成员对象?
请考虑以下示例。这是没关系的,或者是否可能在调用DoBar()之后创建_bar
?
class Bar
{
public:
Set(int i){_ i = i; }
私人:
int _i;
};
class Foo
{
public:
Foo(){DoBar(); }
private:
void DoBar(){_ bar.Set(10); }
Bar _bar;
};
提前致谢,
Joost
-----
人们的古代历史概念是星际迷航的第一个系列
可以耐心对待,因为通常不是他们的错,所以他们被减少为从学校接受教育。 - Terry Pratchett
Are member objects constructed before the body of the constructor executes?
Consider the following example. Is this okay or is it possible that _bar
will be created after the call to DoBar()?
class Bar
{
public:
Set(int i) { _i = i; }
private:
int _i;
};
class Foo
{
public:
Foo() { DoBar(); }
private:
void DoBar() { _bar.Set(10); }
Bar _bar;
};
Thanks in advance,
Joost
-----
"People whose concept of ancient history is the first series of Star Trek
may be treated with patience, because it''s usually not their fault they were
reduced to getting their education from school." -- Terry Pratchett
推荐答案
[snip]
[snip]
没有。
No.
Umm这是一个/或者问题。 :-)我认为他的意思是不:_bar不会在调用DoBar()之后创建
,但是已经由
时间创建了 。换句话说,是的,没关系。
Umm that was an either/or question. :-) I think he means "no: _bar will not
be created after the call to DoBar(), but will be already be created by that
time". In other words, yes, it''s ok.
[snip]
[snip]
是的。 />
Yes.
否。
No.
嗯这是一个问题。 :-)我认为他的意思是no:_bar不会在调用DoBar()之后创建,但是已经被那个
时间创建了。换句话说,是的,没关系。
Umm that was an either/or question. :-) I think he means "no: _bar will not
be created after the call to DoBar(), but will be already be created by that
time". In other words, yes, it''s ok.
[snip]
[snip]
声明含糊不清:创建Foo后立即创建_bar,并在输入Foo()体之前创建
。当调用DoBar()时,_bar
已经创建了
(其成员_i未初始化)。因此,调用
DoBar,然后调用Bar :: Set,就可以了。
Victor
The statement is ambiguous: _bar is created as soon as Foo is created and
before the body of Foo() is entered. By the time DoBar() is called, _bar
has already been created (with its member _i uninitialised). So, calling
"DoBar", which in turn calls Bar::Set, is OK.
Victor
这篇关于构件对象的构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!