在父对象的构造函数中为子对象提供指向父对象的指针?
give a subobject a pointer to a parent object in the parent object's constructor?
我正在尝试找到一种简单的方法,将"此"指针的值分配给另一个指针。我想这样做的原因是,我可以将自动指针用于每个种子的父苹果对象。我知道我可以手动将父苹果的地址分配给种子:myapple.itsseed-> parentApple =&myApple;但是我正在尝试使用"这个"指针找到一种更方便地做到这一点的方法。让我知道这是否推荐/可能,如果是 - 告诉我我做错了什么。
这就是我现在拥有的:
main.cpp:
#include <string>
#include <iostream>
#include "Apple.h"
#include "Seed.h"
int main()
{
///////Apple Objects Begin///////
Apple MyApple;
Seed MySeed;
MyApple.ItsSeed = &MySeed;
MyApple.Name = "Bob";
MyApple.ItsSeed->ParentApple = &MyApple;
std::cout << "The name of the apple is " << MyApple.Name <<".n";
std::cout << "The name of the apple's seed's parent apple is " << MyApple.ItsSeed->ParentApple->Name <<".n";
std::cout << "The address of the apple is " << &MyApple <<".n";
std::cout << "The address of the apple is " << MyApple.ItsSeed->ParentApple <<".n";
return 0;
}
苹果:
#ifndef APPLE_H
#define APPLE_H
#include <string>
#include "Seed.h"
class Apple {
public:
Apple();
std::string Name;
int Weight;
Seed* ItsSeed;
};
#endif // APPLE_H
Apple.cpp:
#include "Apple.h"
#include "Seed.h"
Apple::Apple()
{
ItsSeed->ParentApple = this;
}
seed.h:
#ifndef SEED_H
#define SEED_H
#include <string>
class Apple;
class Seed {
public:
Seed();
std::string Name;
int Weight;
Apple* ParentApple;
};
#endif // SEED_H
seed.cpp:
#include "Seed.h"
Seed::Seed()
{
}
一切都很好。但是,每当我不注入itseed-> parentApple = this;该程序崩溃而无需产生任何输出。这是一个人为证明问题的例子。我觉得问题与滥用"这个"指针有关,或者可能与某种圆形循环有关。但是我不确定 - 我没有得到很好的结果,将"此"的价值分配给任何东西。谢谢。
这是可以预期的,因为当时您还没有将ItsSeed
初始化为任何内容;您正在删除一个非初始化的指针。这触发了未定义的行为,在此特定实例中,这引起了崩溃。
您需要在尝试解释之前初始化指针的指针。
例如,您可以使用一对构造函数,并且只有在给出了非编号指针时才设置种子的parentapple字段:
Apple::Apple() : ItsSeed(NULL)
{
}
Apple::Apple(Seed * seed) : ItsSeed(seed)
{
if (seed) {
seed->ParentApple = this;
}
}
您的程序崩溃,因为您没有使用Seed
的指针初始化的Apple::ItSeed
成员。
相关文章:
- 对象指针在c++中是如何工作的
- C++ 对象指针数组的复制构造函数
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 正确初始化和销毁对象指针的C++数组?
- 如何深度复制链表对象指针
- 对象指针 c++ 的全局向量错误
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 静态对象指针
- 正在将对象指针数组初始化为NULL
- 如何使用条件表达式返回对象指针?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 使用C对象指针构建PyObject*
- 如何在使用对象指针时访问成员函数
- 静态强制转换允许转换对象指针,但不允许转换整数
- C++ abort() 在函数内的抽象类对象指针调用上
- 指向函数的对象指针
- 访问指向对象指针向量的指针的第一个元素?
- 如何将对象/指针正确存储到 Qlist 中
- 对象指针打印结果以相反的顺序进行