没有警告,没有错误。编译正常,但在更新功能的底部,以下行使程序崩溃:
(*m_mousePosition).setX(event.motion.x);
(*m_mousePosition).setY(event.motion.y);
这是完整的代码:
#include <SDL2/SDL.h>
#include <vector>
#include "Vector2D.h"
using namespace std;
#ifndef INPUTHANDLER_H
#define INPUTHANDLER_H
enum mouse_buttons{
LEFT = 0,
MIDDLE = 1,
RIGHT = 2
};
class InputHandler{
public:
static InputHandler* Instance(){
if(s_pInstance==0){
s_pInstance= new InputHandler();
}
return s_pInstance;
}
void update(){
if(event.type == SDL_MOUSEBUTTONDOWN){
if(event.button.button == SDL_BUTTON_LEFT){
m_mouseButtonStates[LEFT]=true;
}
if(event.button.button == SDL_BUTTON_MIDDLE){
m_mouseButtonStates[MIDDLE]=true;
}
if(event.button.button == SDL_BUTTON_RIGHT){
m_mouseButtonStates[RIGHT]=true;
}
}
if(event.type == SDL_MOUSEBUTTONUP){
if(event.button.button == SDL_BUTTON_LEFT){
m_mouseButtonStates[LEFT]=false;
}
if(event.button.button == SDL_BUTTON_MIDDLE){
m_mouseButtonStates[MIDDLE]=false;
}
if(event.button.button == SDL_BUTTON_RIGHT){
m_mouseButtonStates[RIGHT]=false;
}
}
if(event.type == SDL_MOUSEMOTION){
(*m_mousePosition).setX(event.motion.x);
(*m_mousePosition).setY(event.motion.y);
}
}
SDL_Event* getEvent(){
return &event;
}
void clear();
bool getMouseButtonStates(int buttonNumber){
return m_mouseButtonStates[buttonNumber];
}
Vector2D* getMousePosition(){
return m_mousePosition;
}
private:
SDL_Event event;
vector<bool> m_mouseButtonStates;
Vector2D* m_mousePosition;
InputHandler(){
for(int i=0; i<3; i++){
m_mouseButtonStates.push_back(false);
}
}
~InputHandler(){}
static InputHandler* s_pInstance;
};
typedef InputHandler TheInputHandler;
#endif /* INPUTHANDLER_H */
也许这是一个问题,但我不知道,我无法解决
==============================新编辑=============== =======================
现在我没有使用指针,但我必须初始化Vector2D
两个参数。我把它放在InputHandler
构造函数中:
InputHandler::InputHandler():m_position(0,0){
for(int i=0; i<3; i++){
m_mouseButtonStates.push_back(false);
}
}
并给我以下错误:
InputHandler.cpp:12:30: error: member initializer 'm_position' does not name a non-static data member or base class
InputHandler::InputHandler():m_position(0,0){
^~~~~~~~~~~~~~~
Vector2D
类的定义:
#include<math.h>
using namespace std;
#ifndef VECTOR2D_H
#define VECTOR2D_H
class Vector2D {
public:
Vector2D(float x, float y):m_x(x), m_y(y){}
float getX(){return m_x;}
float getY(){return m_y;}
void setX(float x){m_x=x;}
void setY(float y){m_y=y;}
float length(){return sqrt(m_x*m_x + m_y*m_y);}
private:
float m_x;
float m_y;
};
#endif /* VECTOR2D_H */
答案 0 :(得分:1)
是的,问题就是你提出的“指针”。
m_mousePosition
已声明,但您从未向其分配任何内容,因此它为NULL / garbage。
你可能不需要在这里使用指针。