繁体   English   中英

C ++初学者:通过引用将b2Body的指针传递给函数

[英]C++ beginner: Passing a pointer of b2Body to function by reference

为了我的一生,我无法弄清楚如何通过引用将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);

假设thing->GetBody()返回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对象。

使用(b2Body*&)将引用传递给指针。

在通话中,您应该像下面那样传递指针的地址:

 GetContactInfo(hero, ground);

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

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

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.

我更喜欢第一种方式,因为它更清洁,更现代。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM