通过另一个对象C++的字段中的指针访问对象
Access an object through a pointer in a field of another object C++
我有两个类声明如下:
(假设所有其他字段、方法、定义和包含都存在且工作正常)
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
是一个Child
。value
移动到"子级"(就像您在更新中所做的那样),代码应输出预期的值。
相关文章:
- 通过指向指针数组的指针访问子类的属性
- 使用指针访问数组中的对象数据成员
- 无法通过指针访问对象的成员
- decltype:使用指针访问类的静态成员
- 是否可以使用指针访问变量以避免直接编辑变量?
- 为什么 C++ 地址中的矢量无法通过原始指针访问
- 使用指针访问数组元素时出现意外结果
- 使用指针访问数组的值
- C++继承从基类指针访问派生类中的非虚拟函数
- 如何使用指针访问成对向量的元素
- 为什么有些库提供无指针访问,而另一些库则不提供
- 如何通过引用或指针访问二维矢量
- 使用指针访问参数接收的结构中的元素时内存泄漏
- 我正在学习C++,我不能使用指针访问参考吗?(举个例子)
- 复制堆栈上的成员值或使用指针访问它?
- C++娜娜 如何从全局列表框*指针访问列表框内的索引 0 上的按钮?
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 从指针访问 Kaguya Lua 状态
- 说明通过指针访问非静态类成员函数
- 有没有办法使用初始化到第一行的指针访问 2d 数组的第二行?