<<运算符不能正确计算表达式

时间:2014-11-08 12:03:08

标签: c++ stream overloading operator-keyword

我用c ++制作了一个Vector类,我的问题是如果我做了

Vector v = v1 + v2;
cout << v

结果是正确的,但是这样做 cout << v1 + v2给出了

[-1.07374e+008 -1.07374e+008 -1.07374e+008]代替[1, 2, 4]

我实施的其他运营商也一样, 这是我的+运算符实现

Vector& Vector::operator+= (const Vector& other) {
    x += other.x;
    y += other.y;
    z += other.z;
    return *this;
}

Vector& operator+ (const Vector& v1, const Vector& v2) {
    Vector v = v1;
    v += v2;
    return v;
}

和&lt;&lt;操作

ostream& operator<< (ostream& o, const Vector& v) {
    o << "[" << v.x << " " << v.y << " " << v.z << "]; ";
    return o;
}

我没有找到错误,我在这里看到的是正确的。任何人都可以说出为什么会这样?

1 个答案:

答案 0 :(得分:1)

按值返回新向量:

Vector operator+ (const Vector& v1, const Vector& v2)
//    ^ no '&'

您将返回对本地变量的引用,该变量在您使用引用时已被销毁。你的编译器应该警告这个;确保你在编译时启用了所有明智的警告。

相关问题