通过另一个对象C ++的字段中的指针访问对象

时间:2017-01-01 22:52:34

标签: c++ oop pointers

我有两个类声明如下:
(假设所有其他字段,方法,定义和包含都存在并且正常工作)

class Child
{
    public:
        Child* parent;
        int value;

    //other fields and methods not listed
};

class Container : public Child
{
    public:
        void addChild(Child &);

    private:
        std::vector<Child *> children;

    //other fields and methods not listed
};

addChild方法:

void Container::addChild(Child &c)
{
    c.parent = this;
    children.push_back(&c);
}

将Child对象添加到Container对象中的向量时,Container对象的地址将分配给Child对象中的父字段。

在以下代码中

Container container;
Child child;

//value could be any number, for testing only.
container.value = 10;
//child is added to the container
container.addChild(child);

//Will print the same address
printf("%x, %x\n", &container, child.parent);

//This is where the problem occurs
printf("%d, %d\n", container.value, child.parent->value);
//10 should be printed both times

在最后一个声明中,不是10次打印两次,而是第一个%d将打印10,但第二个%d将打印0。

我不知道为什么会发生这种情况,我正在寻找一种方法让Child对象存储指向其父对象的指针并检索父对象的字段,而不会出现此问题。

1 个答案:

答案 0 :(得分:0)

与WhozCraig所说,child.parentChild。将value移动到Child(正如您在更新中所做的那样),代码应输出预期值。