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

Access an object through a pointer in a field of another object C++

本文关键字:指针 访问 对象 字段 一个对象 C++      更新时间:2023-10-16

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

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 对象添加到容器对象中的

向量时,容器对象的地址将分配给 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, %xn", &container, child.parent);
//This is where the problem occurs
printf("%d, %dn", container.value, child.parent->value);
//10 should be printed both times

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

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

就像WhozCraig说的,child.parent是一个Childvalue移动到"子级"(就像您在更新中所做的那样),代码应输出预期的值。