0

对于我的生活,我无法弄清楚如何通过引用将 b2Body(Box2d 对象)传递给方法并为其赋值。

void GameContactListener::GetContactInfo(b2Body &hero, b2Body &ground, b2Body &enemy) {
    b2Body *b1 = thing1->GetBody();
    b2Body *b2 = thing2->GetBody();

    // EXC_BAD_ACCESS HERE
    hero = *b1;
    ground = *b2;
}

// elsewhere
b2Body *hero = NULL;
b2Body *ground = NULL;

GetContactInfo(*hero, *ground);

我可以通过引用为简单int类型工作,但似乎缺少指针。

编辑,添加方法声明:

void GetContactInfo(b2Body& hero,  b2Body& ground, b2Body& enemy);
4

4 回答 4

1

假设thing->GetBody()返回 a b2Body*,则

void GameContactListener::GetContactInfo(b2Body*& hero, b2Body*& ground) {
    hero = thing->GetBody();
    ground = thing->GetBody();
}

// elsewhere
b2Body* hero = NULL;
b2Body* ground = NULL;

GetContactInfo(hero, ground);

请注意,两者都heroground指向同一个b2Body对象。

于 2013-01-22T16:39:40.223 回答
0

用于(b2Body*&)传递对指针的引用。

于 2013-01-22T16:39:47.003 回答
0

在您的通话中,您应该传递指针的地址,如下所示:

 GetContactInfo(hero, ground);

我建议您阅读本教程的第 4 节。

于 2013-01-22T16:39:58.453 回答
0

正如其他人指出的那样,使用对指针的引用来更改指针。

void
GameContactListener::GetContactInfo(b2Body *& hero, b2Body *& ground)
{
    b2Body *b1 = thing->GetBody();
    b2Body *b2 = thing->GetBody();

    // Assign pointer to ref to pointer here.
    hero = b1;
    ground = b2;
}

// elsewhere
b2Body *hero = NULL;
b2Body *ground = NULL;

GetContactInfo(hero, ground); // Pass pointers

另一种老式的方法是指针指针:

void
GameContactListener::GetContactInfo(b2Body **hero, b2Body **ground) {
    b2Body *b1 = thing->GetBody();
    b2Body *b2 = thing->GetBody();

    // Assign pointers to pointers.
    *hero = b1;
    *ground = b2;
}

// elsewhere
b2Body *hero = NULL;
b2Body *ground = NULL;

GetContactInfo(&hero, &ground); // Pass address of pointers.

I like the first way better as it's cleaner and more modern.

于 2013-01-22T16:49:14.967 回答