成员指针指向成员对象和声明顺序
#include <iostream>
class FooParent
{
public:
FooParent(int* new_p_bar)
{
p_bar = new_p_bar;
}
public:
int* p_bar;
};
class FooChild : public FooParent
{
public:
int bar;
public:
FooChild(int new_x)
:FooParent(&bar)
,bar(new_x) \\ point of concern
{}
};
int main()
{
FooChild foo(8);
std::cout << foo.bar << std::endl;
}
上面的例子工作原理就像我想要的。将指针 p_bar
链接到 bar
。但是,我的问题是我指向的构造函数尚未被调用的成员。
The above example works as I want it to .i.e. link the pointer p_bar
to bar
. However, my concern is that I am pointing to a member whose constructor is not yet called.
这个代码是否有效,或者标准有什么要说的。
Is this code valid, or does the standard have something to say about it. If not what is the alternative.
注意:在我的应用程序 bar
对象 Bar
(不是 int
),这有什么含义吗?
NOTE: In my application bar
is an Object Bar
(not int
), does this have any implications?
看看这个:
class FooParent {
public:
FooParent(int* new_p_bar)
{
p_bar = new_p_bar;
*p_bar = 99; // this has no sense
}
void set99() {
*p_bar = 99; // this - has
}
public:
int* p_bar;
};
class FooChild : public FooParent
{
public:
int bar;
public:
FooChild(int new_x)
:FooParent(&bar)
,bar(new_x) // point of concern
{}
};
int main()
{
FooChild foo( 42 );
std::cout << foo.bar << std::endl;
foo.set99();
std::cout << foo.bar << std::endl;
}
LWS 。
我的意思是如果 FooParent
构造函数只向外部存储指针 int
(或 Bar
- 无关紧要)
I mean that if FooParent
's constructor only stores a pointer to external int
(or Bar
- doesn't matter) then there will be no problem.
另一方面,如果您给予 bar code>到
FooParent
- 像这样
In other hand, if you'll give a copy of bar
to FooParent
- like this
class FooParent
{
public:
FooParent(Bar new_p_bar)
{
p_bar = new_p_bar;
}
void set99() {
p_bar = 99; // this - has
}
public:
Bar p_bar;
};
class FooChild : public FooParent
{
public:
Bar bar;
public:
FooChild(Bar new_x)
:FooParent(bar)
,bar(new_x) // point of concern
{}
};
int main()
{
FooChild foo( 42 );
std::cout << foo.bar << std::endl;
foo.set99();
std::cout << foo.bar << std::endl;
}
LWS 。
这不会工作。即使 Bar
将有一个副本操作符或/和赋值运算符
this will not work. Even if Bar
will have a copy c-tor or/and assignment operator