首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运算符重载奇怪的结果

运算符重载奇怪的结果
EN

Stack Overflow用户
提问于 2011-07-18 10:04:50
回答 3查看 113关注 0票数 0

这是我的班级

代码语言:javascript
复制
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;
}

当我尝试使用更复杂的方程时,我得到了不正确的结果。例如,这是可行的:

代码语言:javascript
复制
Vector vChange = velocity * time;
position += vChange;

而这不是:

代码语言:javascript
复制
position += velocity * time;

也就是说,它编译并运行,但将一些伪代码写入位置

这个也是一样的:

代码语言:javascript
复制
Vector& Reflect(const Vector& I, const Vector& N)
{
Vector v = I - 2 * Dot(N, I) * N;
}

你能告诉我我哪里做错了吗?谢谢!

EN

回答 3

Stack Overflow用户

发布于 2011-07-18 10:07:57

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

代码语言:javascript
复制
Vector Vector::operator*(float n) const
{
    Vector result = *this;
    result.x *= n;
    result.y *= n;
    result.z *= n;
    return result;
}

operator+也是如此。

票数 5
EN

Stack Overflow用户

发布于 2011-07-18 10:09:04

对于您的operator*operator+,您必须按值返回Vector,而不是通过引用。你所做的就是返回一个悬空的引用,这是未定义的行为。

票数 2
EN

Stack Overflow用户

发布于 2011-07-18 10:08:25

您将返回一个对局部变量的引用。别干那事。非赋值运算符应该按值返回,而不是按引用返回。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6728073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档