gpt4 book ai didi

c++ - 运算符重载奇怪的结果

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:58 24 4
gpt4 key购买 nike

这是我的类(class)

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;
}

你能告诉我我做错了什么吗?谢谢!

最佳答案

您正在返回对 operator* 中局部变量的引用。那是未定义的行为。改为按值返回:

Vector Vector::operator*(float n) const
{
Vector result = *this;
result.x *= n;
result.y *= n;
result.z *= n;
return result;
}

同样适用于operator+

关于c++ - 运算符重载奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6728073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com