gpt4 book ai didi

c++ 使用 "*"运算符没有运算符匹配这些操作数

转载 作者:行者123 更新时间:2023-11-28 00:00:20 24 4
gpt4 key购买 nike

我在我的课上有简单的运算符重载

class Vec2
{
public:
Vec2(float x1,float y1)
{
x = x1;
y = y1;
}
float x;
float y;
};

class FOO {
private:
friend Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
{
return Vec2(point1.x * point2.x, point1.y * point2.y);
}

Vec2 mul(Vec2 p);
};

Vec2 FOO::mul(Vec2 p)
{
Vec2 point = p * Vec2(1,-1);
return point;
}

但是这个乘法给我这个错误:

operator* no operator matches these operands

问题是我无法更改 Vec2 类,所以我需要全局运算符重载

最佳答案

operator* 定义不应该在 class FOO 中。将它放在任何类定义之外:

inline Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
{
return Vec2(point1.x * point2.x, point1.y * point2.y);
}

如果这是在头文件中,则需要 inline 关键字。然后,您可以在 FOO 和其他任何地方使用运算符。

不可能将运算符限制为只能在 FOO 方法中使用。函数可见性不是那样工作的。您可以做的最接近的事情是仅在某些也具有使用点的 .cpp 文件中声明 operator* 重载,并将其标记为 static 或匿名命名空间。

关于c++ 使用 "*"运算符没有运算符匹配这些操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39565922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com