所以我一直在阅读Shaun Mitchell的《SDL Game Development》一书。我在使用书中的代码时遇到了一些小问题,但到目前为止,我已经能够自己找出并纠正它,但这一个让我陷入了困境。
程序可以正常编译,但是由于seg错误而崩溃。
这是书上让我写的Vector2D类:
#ifndef __Vector2D__
#define __Vector2D__
#include <math.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); }
Vector2D operator+(const Vector2D& v2) const
{
return Vector2D(m_x + v2.m_x, m_y + v2.m_y);
}
friend Vector2D& operator+=(Vector2D& v1, const Vector2D& v2)
{
v1.m_x += v2.m_x;
v1.m_y += v2.m_y;
return v1;
}
Vector2D operator*(float scalar)
{
return Vector2D(m_x * scalar, m_y * scalar);
}
Vector2D& operator*=(float scalar)
{
m_x *= scalar;
m_y *= scalar;
return *this;
}
Vector2D operator-(const Vector2D& v2) const
{
return Vector2D(m_x - v2.m_x, m_y - v2.m_y);
}
friend Vector2D& operator-=(Vector2D& v1, const Vector2D& v2)
{
v1.m_x -= v2.m_x;
v1.m_y -= v2.m_y;
return v1;
}
Vector2D operator/(float scalar)
{
return Vector2D(m_x / scalar, m_y / scalar);
}
Vector2D& operator/=(float scalar)
{
m_x /= scalar;
m_y /= scalar;
return *this;
}
void normalize()
{
float l = length();
if (l > 0)
{
(*this) *= 1 / 1;
}
}
private:
float m_x;
float m_y;
};
#endif // __Vector2D__
这是一个Player类的输入处理事件,程序开始崩溃:
void Player::handleInput()
{
Vector2D* vec = TheInputHandler::Instance()->getMousePosition();
m_velocity = (*vec - m_position) / 100;
}
当m_velocity = (*vec - m_position)/100;这当然可以追溯到我的Vector2D类的操作符-。m_velocity和m_position都是矢量。用+替换-也会产生同样的崩溃
任何可能有问题的帮助都会非常感激。
Vector2D* vec = TheInputHandler::Instance()->getMousePosition();
您将其设置为指针,但从未为其分配内存。(除非那个函数就是这样做的…?)
如果你不打算把它传递到任何地方,就没有必要把它变成一个指针