2012-12-26 36 views
3

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

+0

我不明白你的要求。你似乎正在尋找一個寫這個'這個'的地方,而沒有任何具體的需要。 –

+0

@Lightness在軌道上的比賽對於我想要做的事情有一個實際目的 - 但我同意它可能是一個簡單的錯誤解釋和損壞。 – Stepan1010

回答

4

這是意料之中的,因爲你沒有初始化ItsSeed在該點什麼;您正在取消引用未初始化的指針。這觸發了未定義的行爲,在這個特定的實例中導致了崩潰。

你需要嘗試取消引用之前將其指針初始化的東西非空。

例如,可以使用一對構造函數,只有當您已獲得一個非空指針設置種子的ParentApple領域:

Apple::Apple() : ItsSeed(NULL) 
{ 
} 

Apple::Apple(Seed * seed) : ItsSeed(seed) 
{ 
    if (seed) { 
     seed->ParentApple = this; 
    } 
} 
+0

我知道這是一樣的,但it'd最好使用'ItsSeed',而不是'seed' –

+0

@ K-BALLO也許在構造函數中,也許不是。堆棧本地更容易被緩存在寄存器IIRC中。在這種情況下,這可能並不重要,但是在一個更詳細的例子中,兩者之間的區別可能很重要。當然,這是微型優化,但如果兩者之間確實沒有行爲差異,那麼它就不是那麼重要。 – cdhowie

0

你的程序崩潰是因爲你沒有Apple::ItSeed構件的指針的Seed有效實例初始化。

相關問題