【发布时间】:2017-03-17 19:23:44
【问题描述】:
我在函数项目中收到错误“Error (active) E0349 no operator "*" matches these operands... operand types are: const Vec2 * float”。我已经定义了 operator * 并且看起来参数匹配......我看不出我做错了什么......
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()));
}
};
【问题讨论】:
-
题外话:执行
x * x比pow(x, 2)效率更高。 -
顺便说一句,类方法和成员不需要使用
this指针。例如,您可以直接拨打Dot,也可以拨打MagnitudeSq。 -
@ThomasMatthews,另一方面,the compiler is pretty good at optimizing。
标签: c++ class operator-overloading