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

发布于 2025-01-08 04:00:04 字数 1062 浏览 0 评论 0原文

我创建了这个结构:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韵柒 2025-01-15 04:00:04
body1->SetUserData(&bodyData);

您将正文数据设置为指针的地址 bodyData。您不希望这样,您希望将其设置为 bodyData。所以:

body1->SetUserData(bodyData);
body1->SetUserData(&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 to bodyData. So:

body1->SetUserData(bodyData);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文