2017-03-17 53 views
0

我在函數Project中收到錯誤「Error (active) E0349 no operator "*" matches these operands... operand types are: const Vec2 * float」。我定義的operator *,它似乎像參數相匹配......我不明白,我做錯了..沒有操作符「*」匹配這些操作數...操作數類型是:const Vec2 * float

class Vec2 
{ 
public: 
    float x; 
    float y; 

    Vec2 operator*(const float &right) { 
     Vec2 result; 
     result.x = x * right; 
     result.y = y * right; 
     return result; 
    }  

    float MagnitudeSq() const 
    { 
     return sqrt(x * x + y * y); 
    } 

    float DistanceSq(const Vec2& v2) 
    { 
     return pow((v2.x - x), 2) + pow((v2.y - y), 2); 
    } 

    float Dot(const Vec2& v2) 
    { 
     return x*v2.x + y*v2.y; 
    } 

    Vec2 Project(const Vec2& v2) 
    { 
     *this = v2 * std::fmax(0, std::fmin(1, (*this).Dot(v2)/this->MagnitudeSq())); 
    } 
}; 
+2

題外話:執行'x * x'比'pow(x,2)'更有效率。 –

+2

順便說一下,類方法和成員不需要使用'this'指針。例如,你可以直接調用'Dot'以及'MagnitudeSq'。 –

+1

@ThomasMatthews,另一方面,[編譯器非常擅長優化](https://godbolt.org/g/PBnZaN)。 – chris

回答

2

你應該申報的vec2operator *作爲行事的const對象。

Vec2 operator*(const float &right) const { 
//        ^^^^^^ 

這是因爲該方法Vec2 Project(const Vec2& v2)您正在使用的運營商*您已在其聲明中的原型常量v2

3

更改線路

Vec2 operator*(const float &right) { 

Vec2 operator*(const float &right) const { 

,它應該工作。

您正嘗試在const對象上執行一個非const成員函數。

相關問題