2012-02-22 62 views
1

我創建這個結構:爲什麼這個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」。

我錯過了什麼?

回答

4
body1->SetUserData(&bodyData); 

你定身的數據是指針bodyData地址。你不想要那個,你想把它設置爲bodyData。所以:

body1->SetUserData(bodyData); 
相關問題