2015-03-19 60 views
0

考慮下面的類聲明的Cocos2D-X的AppDelegate數據成員初始化丟失

class AppDelegate : private cocos2d::Application 
{ 
private: 
    int _test; 
    // .... 
}; 

我初始化數據成員int _test作爲

AppDelegate::AppDelegate() : _test(20) { 
    cocos2d::log("Initialzing %p with _test = %d", this, _test); 
} 

後來,當代碼

bool AppDelegate::applicationDidFinishLaunching() { 
    cocos2d::log("Checking %p, found _test = %d", this, _test); 
    // .... 
} 
執行

,輸出爲

Initialzing 0x10da4aa20 with _test = 20 
// .... 
Checking 0x10da4aa20, found _test = 1056964608 

這表示_test未初始化。這個問題似乎是特定於cocos2d-x體系結構的,因爲我無法在沙箱項目中重現此操作(其中AppDelegate已更換爲更簡單的類)。

我的問題是:爲什麼這個初始化會丟失?在AppDelegate類中是否有另一種初始化和使用數據成員的方法?

+0

您有自定義的複製構造函數或複製賦值運算符嗎? – 2015-03-19 08:48:03

+0

不,沒有自定義的複製構造函數或複製賦值操作符。 – conciliator 2015-03-19 09:02:50

+0

我不熟悉cocos2dx.I記得每個類都有一個名稱爲「init」的函數。它們在構造函數之後被調用。也許這個函數使它... – 2015-03-19 09:13:11

回答

0

所以判明爲PhysicsMaterial構造函數中執行的_test數據成員改變:

typedef struct CC_DLL PhysicsMaterial 
{ 
    float density;   ///< The density of the object. 
    float restitution;  ///< The bounciness of the physics body. 
    float friction;   ///< The roughness of the surface of a shape. 

    PhysicsMaterial() 
    : density(0.0f) 
    , restitution(0.0f) 
    , friction(0.0f) 
    {} 

    PhysicsMaterial(float aDensity, float aRestitution, float aFriction) 
    : density(aDensity) 
    , restitution(aRestitution) 
    , friction(aFriction) 
    {} // Watch reveals that this was the culprit ... 
}PhysicsMaterial; 

顯然,在此構造沒有代碼,應該改變_test成員的值,這表明之前的版本有問題。

清潔和隨後的完全重建解決了這個問題。