我試圖找到一個簡單的方法來了「這個」指針的值賦給另一個指針。我希望能夠做到這一點的原因是,我可以擁有一個指向每個種子的父蘋果對象的自動指針。我知道我可以手動將父蘋果的地址分配給種子,例如: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