我试图找到一种简单的方法将“this”指针的值分配给另一个指针。我希望能够做到这一点的原因是我可以拥有一个指向每个种子的父苹果对象的自动指针。我知道我可以手动将父苹果的地址分配给种子:MyApple.ItsSeed->ParentApple = &MyApple; 但我试图找到一种使用“this”指针更方便地执行此操作的方法。让我知道这是否被推荐/可能,如果是的话 - 告诉我我做错了什么。
这就是我现在所拥有的:
主.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;
}
苹果.h:
#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
苹果.cpp:
#include "Apple.h"
#include "Seed.h"
Apple::Apple()
{
ItsSeed->ParentApple = this;
}
种子.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
种子.cpp:
#include "Seed.h"
Seed::Seed()
{
}
一切都编译得很好。但是每当我取消注释 ItsSeed->ParentApple = this; 程序崩溃而不产生任何输出。这是一个人为的例子来演示这个问题。我觉得这个问题与“this”指针的滥用有关,或者它可能与某种循环循环有关。但我不确定 - 将“this”的值分配给任何东西都没有得到好的结果。谢谢。