2011-07-18 7 views
0

을 heres 내 수업연산자 오버로딩 이상한 결과

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

내가 뭘 잘못하고 있는지 조언 해 줄 수 있니? 감사!

+1

[연산자 오버로딩 FAQ] (http://stackoverflow.com/q/4421706/46642)를 읽어 보는 것이 좋습니다. –

답변

5

operator*에 로컬 변수에 대한 참조를 반환합니다. 그건 정의되지 않은 행동입니다. 값으로 대신 반환 :

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

operator+과 동일합니다.

1

로컬 변수에 대한 참조가 반환됩니다. 그러지 마. 귀하가 지정하지 않은 운영자는 참조가 아닌 가치에 의해 반환해야합니다.

2

operator*operator+은 참조가 아닌 Vector을 반환해야합니다. 당신이 가지고있는 것은 매달려있는 참조를 되돌려 보내는 것입니다. 이것은 정의되지 않은 동작입니다.

+0

여전히 + =에 대한 참조를 반환하겠습니까? –

+0

@Mikhail : 그렇습니다.이 경우에는'this'를 반환하고 범위를 벗어나는 지역 변수는 반환하지 않기 때문입니다. –