2017-03-17 57 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成员函数。

相关问题