【发布时间】:2013-03-19 22:46:49
【问题描述】:
我已经问过this 的问题。我现在的问题是这是如何工作的?详细地说,我怎样才能指向一个尚未初始化的对象。我已经制作了这个 MWE,它表明该对象是创建的副本而不是分配的副本。即该对象尚未初始化,但我可以指向它。
#include <iostream>
class Foo {
public:
int x;
Foo(const Foo& ori_foo) {
std::cout << "constructor" << std::endl;
x = ori_foo.x;
}
Foo& operator = (const Foo& ori_foo) {
std::cout << "operator =" << std::endl;
x = ori_foo.x;
return *this;
}
Foo(int new_x) {
x = new_x;
}
};
class BarParent {
public:
Foo *p_foo;
BarParent(Foo* new_p_foo) : p_foo(new_p_foo)
{
std::cout << (*new_p_foo).x << std::endl;
}
};
class BarChild : public BarParent {
public:
Foo foo;
BarChild(Foo new_foo)
:BarParent(&foo) //pointer to member not yet initialised
,foo(new_foo) // order of initilization POINT OF INTEREST
{}
};
int main() {
Foo foo(101);
BarChild bar(foo);
std::cout << bar.p_foo->x << std::endl;
std::cout << bar.foo.x << std::endl;
}
输出:
constructor
0
constructor
101
101
不要害怕深入了解如何处理内存的细节。而且,每个成员都居住在哪里。
【问题讨论】:
-
如果还不清楚请告诉我
-
抱歉有错误现在编辑了
:BarParent(&foo) -
你试过在 BarParent 构造函数中打印 Foo 的值吗?
-
你的例子的一个问题是你从来没有真正使用过 bar.p_foo,所以它可以是没有任何问题的任何东西。
-
我的猜测是,即使成员
Foo尚未初始化,在调用基本构造函数之前已经为它(以及所有其他成员变量)分配了空间。这将允许您传递指向该空间的指针,即使它未初始化。
标签: c++ pointers inheritance member