2012-12-26 104 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有效实例初始化。

相关问题