我有一个带有静态成员的班级MotionDirection
。该类的源代码如下。但我无法初始化类的静态成员,我可以得到原因。所以问题出在MotionDirection.cpp
,请参阅注释以了解有关编译器错误的详细信息。
MotionDirection.h
#ifndef MOTION_DIRECTION
#define MOTION_DIRECTION
namespace game{
class IntPosition;
class MotionDirection {
private:
IntPosition* positionDisplacement;
float angle;
MotionDirection* returnDirection;
public:
MotionDirection( IntPosition* positionDisplacement, float angle );
void setReturnDirection ( MotionDirection* returnDirection );
IntPosition* getPositionDisplacement();
float getAngle();
MotionDirection* getReturnDirection();
static MotionDirection* NONE;
static MotionDirection* LEFT;
static MotionDirection* RIGHT;
static MotionDirection* UP;
static MotionDirection* DOWN;
static void initStatics();
};
}
#endif
MotionDirection.cpp
#include "MotionDirection.h"
#include "IntPosition.h"
namespace game{
MotionDirection::NONE = new MotionDirection ( new IntPosition( 0, 0), 0.0f );
// here I get an error:
// MotionDirection.cpp:10:5: error: 'NONE' in 'class game::MotionDirection' does not name a type
MotionDirection::MotionDirection( IntPosition* positionDisplacement, float angle ) {
this->positionDisplacement = positionDisplacement;
this->angle = angle;
}
void MotionDirection::setReturnDirection ( MotionDirection* returnDirection ) {
this->returnDirection = returnDirection;
}
IntPosition* MotionDirection::getPositionDisplacement() {
return positionDisplacement;
}
float MotionDirection::getAngle() {
return angle;
}
MotionDirection* MotionDirection::getReturnDirection() {
return returnDirection;
}
void MotionDirection::initStatics () {
MotionDirection::NONE = new MotionDirection ( new IntPosition( 0, 0), 0.0f );
MotionDirection::LEFT = new MotionDirection ( new IntPosition(-1, 0), 180.0f );
MotionDirection::RIGHT = new MotionDirection ( new IntPosition( 1, 0), 0.0f );
MotionDirection::UP = new MotionDirection ( new IntPosition( 0,-1), 90.0f );
MotionDirection::DOWN = new MotionDirection ( new IntPosition( 0, 1), 270.0f );
}
MotionDirection::initStatics();
// or here I get an error:
// MotionDirection.cpp:45:35: error: expected constructor, destructor, or type conversion before ';' token
}
P.S。这是Android-NDK项目,我从cygwin控制台运行编译。
答案 0 :(得分:3)
只需替换
MotionDirection::NONE = new MotionDirection ( new IntPosition( 0, 0), 0.0f );
与
MotionDirection* MotionDirection::NONE = new MotionDirection ( new IntPosition( 0, 0), 0.0f );
注意MotionDirection*
在变量名称之前键入:您需要为编译器提供类型。
您不能将表达式放在功能块之外。有两种方法可以做到“正确”:
1
initStatics()
返回值。initStatics()
来初始化新的静态变量。2
initStatics()
的调用。