c++ - 没有运算符 "*"与这些操作数匹配...操作数类型为 : const Vec2 * float

标签 c++ class operator-overloading

我在函数 Project 中收到错误“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()));
    }
};

最佳答案

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

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

这是因为在 Vec2 Project(const Vec2& v2) 方法中,您在 v2 上使用了您在原型(prototype)中声明为 const 的运算符*。

关于c++ - 没有运算符 "*"与这些操作数匹配...操作数类型为 : const Vec2 * float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865608/

相关文章:

c++ - 我如何检查输入是否是 C++ 中的 int?

java - Ignite C++ 客户端用于 cassandra 集成

c++ - 错误 : No match for 'operator>>' Overloading istream operator

ruby-on-rails - ruby:批量初始化实例变量

excel - 如何使用excel vba将一个事件分配给多个对象?

c++ - 重载的 std::ostream operator<< 未调用,流获取变量地址而不是对象

c# - 隐式转换如何与运算符重载一起使用?

c++ - 您如何设计 C++ 应用程序才能使模拟对象最易于使用?

c++ - 在 firemonkey 中评估 Canvas 渲染的视频卡性能

class - 使用自动生成的公共(public)属性方法与创建访问私有(private)属性的方法