Cocos2d-x中如何声明CCInteger成员变量?


下面这个类在Xcode中可以编译通过.

   
  class Game : public CCLayer
  
{
private:

CCInteger mDirectionUp = CCInteger(TANK_CONTROL_MOVE_UP);
CCInteger mDirectionRight = CCInteger(TANK_CONTROL_MOVE_RIGHT);
CCInteger mDirectionDown = CCInteger(TANK_CONTROL_MOVE_DOWN);
CCInteger mDirectionLeft = CCInteger(TANK_CONTROL_MOVE_LEFT);

};

但是Eclipse为Android中编译通不过.

报错:

   
  jni/../../Game/Game.h:64:60: error: a call to a constructor cannot appear in a constant-expression
  
jni/../../Game/Game.h:64:60: error: ISO C++ forbids initialization of member 'mDirectionUp' [-fpermissive]
jni/../../Game/Game.h:64:60: error: making 'mDirectionUp' static [-fpermissive]
jni/../../Game/Game.h:64:60: error: invalid in-class initialization of static data member of non-integral type 'cocos2d::CCInteger'
jni/../../Game/Game.h:65:66: error: a call to a constructor cannot appear in a constant-expression
jni/../../Game/Game.h:65:66: error: ISO C++ forbids initialization of member 'mDirectionRight' [-fpermissive]
jni/../../Game/Game.h:65:66: error: making 'mDirectionRight' static [-fpermissive]
jni/../../Game/Game.h:65:66: error: invalid in-class initialization of static data member of non-integral type 'cocos2d::CCInteger'
jni/../../Game/Game.h:66:64: error: a call to a constructor cannot appear in a constant-expression
jni/../../Game/Game.h:66:64: error: ISO C++ forbids initialization of member 'mDirectionDown' [-fpermissive]
jni/../../Game/Game.h:66:64: error: making 'mDirectionDown' static [-fpermissive]
jni/../../Game/Game.h:66:64: error: invalid in-class initialization of static data member of non-integral type 'cocos2d::CCInteger'
jni/../../Game/Game.h:67:64: error: a call to a constructor cannot appear in a constant-expression
jni/../../Game/Game.h:67:64: error: ISO C++ forbids initialization of member 'mDirectionLeft' [-fpermissive]

如果修改成:
CCInteger mDirectionUp;
CCInteger mDirectionRight;
CCInteger mDirectionDown;
CCInteger mDirectionLeft;
则报错:
jni/../../Game/Game.h:18:7: error: no matching function for call to 'cocos2d::CCInteger::CCInteger()'

请问该如何解决此问题? 谢谢.

cocos2d-x C++

Wei-Z 11 years, 10 months ago

好吧, 这个是我C++不过关, 我自己贴出答案.

因为CCInteger没有默认的构造函数. 所以类Game的构造函数中必须对其进行初始化.
下面这个写法, 在Xcode, 和Eclipse都编译通过.

   
  //in Game.h
  
class Game : public CCLayer
{
public:
Game();
private:

CCInteger mDirectionUp;
CCInteger mDirectionRight;
};

//in Game.cpp:
Game::Game() : mDirectionUp(0), mDirectionRight(0)
{

}

brenden answered 11 years, 10 months ago

Your Answer