[英]C++ beginner: Passing a pointer of b2Body to function by reference
For the life of me, I can't figure out how to pass a b2Body (Box2d object) to a method by reference and assign it a value. 为了我的一生,我无法弄清楚如何通过引用将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);
I can get pass by reference working for simple int
types but seem to be missing something with pointers. 我可以通过引用传递给简单的
int
类型,但是似乎缺少指针。
Edit, adding declaration of method: 编辑,添加方法声明:
void GetContactInfo(b2Body& hero, b2Body& ground, b2Body& enemy);
Assuming thing->GetBody()
returns a b2Body*
, then 假设
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);
Note that both hero
and ground
will point t the same b2Body
object. 请注意,
hero
和ground
都将指向同一b2Body
对象。
使用(b2Body*&)
将引用传递给指针。
In your call you should pass the address of the pointer like below: 在通话中,您应该像下面那样传递指针的地址:
GetContactInfo(hero, ground);
I advice you to read section 4 in this tutorial . 我建议您阅读本教程的第4节。
Use reference to pointer to change the pointer as others have pointed out. 如其他人指出的那样,使用对指针的引用来更改指针。
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
Another old-fashioned way is pointer to pointer: 另一种老式的方法是指向指针的指针:
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. 我更喜欢第一种方式,因为它更清洁,更现代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.