简体   繁体   English

为什么这个C ++(cocos2d,box2d)示例给出一个指针而不是一个值?

[英]Why does this C++ (cocos2d, box2d) example give a pointer instead of a value?

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: 然后尝试在此处访问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);
    }
}

It displays someNumber as a memory address 6-7 digits long instead of the value "4". 它显示someNumber作为6-7位长的内存地址,而不是值“ 4”。

What am I missing? 我想念什么?

body1->SetUserData(&bodyData);

You're setting the body data to be the address of the pointer bodyData . 您将主体数据设置为指针 bodyData地址 You don't want that, you want to set it to bodyData . 您不需要那样,您可以将其设置为bodyData So: 所以:

body1->SetUserData(bodyData);

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

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