【问题标题】:No operator "*" matches these operands... operand types are: const Vec2 * float没有运算符“*”与这些操作数匹配...操作数类型为: const Vec2 * float
【发布时间】: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 * xpow(x, 2)效率更高。
  • 顺便说一句,类方法和成员不需要使用 this 指针。例如,您可以直接拨打Dot,也可以拨打MagnitudeSq
  • @ThomasMatthews,另一方面,the compiler is pretty good at optimizing

标签: c++ class operator-overloading


【解决方案1】:

您应该将vec2operator * 声明为作用于const 对象。

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

这是因为在 Vec2 Project(const Vec2& v2) 方法中,您在 v2 上使用了 operator*,您已在原型中声明了 const。

【讨论】:

    【解决方案2】:

    换行

    Vec2 operator*(const float &right) {
    

    Vec2 operator*(const float &right) const {
    

    它应该可以工作。

    您现在正尝试对 const 对象执行非 const 成员函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2013-01-25
      相关资源
      最近更新 更多