继承我的班级
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;
}
Run Code Online (Sandbox Code Playgroud)
在尝试使用更复杂的方程式时,我得到的结果不正确.例如这个工作:
Vector vChange = velocity * time;
position += vChange;
Run Code Online (Sandbox Code Playgroud)
而这个DOESNT:
position += velocity * time;
Run Code Online (Sandbox Code Playgroud)
即它编译并运行,但写入一些虚假的位置
同一个:
Vector& Reflect(const Vector& I, const Vector& N)
{
Vector v = I - 2 * Dot(N, I) * N;
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我我做错了什么吗?谢谢!
您将返回对本地变量的引用operator*.这是未定义的行为.按价值返回:
Vector Vector::operator*(float n) const
{
Vector result = *this;
result.x *= n;
result.y *= n;
result.z *= n;
return result;
}
Run Code Online (Sandbox Code Playgroud)
同样的operator+.
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |