这是我的班级
class Vector
{
public:
Vector();
Vector(float x, float y, float z);
float x;
float y;
float z;
Vector &operator+(const Vector &other) const;
Vector &operator+=(const Vector &other);
Vector &operator*(float n) const;
};
//op overloading functions impl
Vector &Vector::operator+(const Vector &other) const
{
Vector result = *this;
result.x += other.x;
result.y += other.y;
result.z += other.z;
return result;
}
Vector &Vector::operator+=(const Vector &other)
{
this->x += other.x;
this->y += other.y;
this->z += other.z;
return *this;
}
Vector &Vector::operator*(float n) const
{
Vector result = *this;
result.x *= n;
result.y *= n;
result.z *= n;
return result;
}当我尝试使用更复杂的方程时,我得到了不正确的结果。例如,这是可行的:
Vector vChange = velocity * time;
position += vChange;而这不是:
position += velocity * time;也就是说,它编译并运行,但将一些伪代码写入位置
这个也是一样的:
Vector& Reflect(const Vector& I, const Vector& N)
{
Vector v = I - 2 * Dot(N, I) * N;
}你能告诉我我哪里做错了吗?谢谢!
发布于 2011-07-18 10:07:57
您返回的是对operator*中局部变量的引用。这是未定义的行为。改为按值返回:
Vector Vector::operator*(float n) const
{
Vector result = *this;
result.x *= n;
result.y *= n;
result.z *= n;
return result;
}operator+也是如此。
发布于 2011-07-18 10:09:04
对于您的operator*和operator+,您必须按值返回Vector,而不是通过引用。你所做的就是返回一个悬空的引用,这是未定义的行为。
发布于 2011-07-18 10:08:25
您将返回一个对局部变量的引用。别干那事。非赋值运算符应该按值返回,而不是按引用返回。
https://stackoverflow.com/questions/6728073
复制相似问题