为什么这个 C++ (cocos2d, box2d) 示例给出一个指针而不是一个值?
我创建了这个结构:
struct MyBodyData
{
int someNumber;
};
然后创建了一个新的主体:
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, -10.0f);
b2Body* body1 = world->CreateBody(&bodyDef);
MyBodyData *bodyData = new MyBodyData();
bodyData->someNumber = 4;
body1->SetUserData(&bodyData);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body1->CreateFixture(&fixtureDef);
然后尝试在此处访问 someNumber:
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
CCLOG(@"Hello One");
MyBodyData* data = (MyBodyData*)b->GetUserData();
if (data!=0 && data->someNumber != 0)
{
int temp;
temp = data->someNumber;
CCLOG(@"Hello Again! %d",temp);
}
}
它将 someNumber 显示为 6-7 位长的内存地址,而不是值“4”。
我缺少什么?
I create this struct:
struct MyBodyData
{
int someNumber;
};
and then created a new body:
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, -10.0f);
b2Body* body1 = world->CreateBody(&bodyDef);
MyBodyData *bodyData = new MyBodyData();
bodyData->someNumber = 4;
body1->SetUserData(&bodyData);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body1->CreateFixture(&fixtureDef);
And then tried to access someNumber here:
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
CCLOG(@"Hello One");
MyBodyData* data = (MyBodyData*)b->GetUserData();
if (data!=0 && data->someNumber != 0)
{
int temp;
temp = data->someNumber;
CCLOG(@"Hello Again! %d",temp);
}
}
It displays someNumber as a memory address 6-7 digits long instead of the value "4".
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将正文数据设置为指针的地址
bodyData
。您不希望这样,您希望将其设置为bodyData
。所以:You're setting the body data to be the address of the pointer
bodyData
. You don't want that, you want to set it tobodyData
. So: