在父对象的构造函数中为子对象提供指向父对象的指针?

give a subobject a pointer to a parent object in the parent object's constructor?

本文关键字:对象 指针 构造函数      更新时间:2023-10-16

我正在尝试找到一种简单的方法,将"此"指针的值分配给另一个指针。我想这样做的原因是,我可以将自动指针用于每个种子的父苹果对象。我知道我可以手动将父苹果的地址分配给种子: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成员。