我试图找到一个简单的方法来了“这个”指针的值赋给另一个指针。我希望能够做到这一点的原因是,我可以拥有一个指向每个种子的父苹果对象的自动指针。我知道我可以手动将父苹果的地址分配给种子,例如:MyApple.ItsSeed-> ParentApple =&MyApple;但我试图找到一种更方便的方法来使用“this”指针。让我知道这是否被推荐/可能,如果是这样 - 告诉我我做错了什么。给子对象一个指向父对象构造函数中父对象的指针?
这就是我现在所拥有的:
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;
}
Apple.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
Apple.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
Seed.cpp:
#include "Seed.h"
Seed::Seed()
{
}
一切编译罚款。但是每当我取消注释ItsSeed-> ParentApple = this;该程序崩溃而不产生任何输出。这是演示问题的一个人为的例子。我觉得这个问题与滥用“this”指针有关,或者它可能与某种循环有关。但我不确定 - 我没有得到很好的结果,将“this”的值赋予任何东西。谢谢。
我不明白你的要求。你似乎正在寻找一个写这个'这个'的地方,而没有任何具体的需要。 –
@Lightness在轨道上的比赛对于我想要做的事情有一个实际目的 - 但我同意它可能是一个简单的错误解释和损坏。 – Stepan1010