0

我有一个MotionDirection带有静态成员的类。该类的源代码如下。但我就是无法初始化类的静态成员,我可以得到原因。所以问题出在 中MotionDirection.cpp,有关编译器错误的详细信息,请参阅注释。

运动方向.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 

运动方向.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

}

PS 这是 Android-NDK 项目,我从 cygwin 控制台运行编译。

4

1 回答 1

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()在其构造函数中写入调用。
  • 添加该嵌套类的私有静态变量。
于 2012-10-13T20:00:53.537 回答