C ++与运营商不匹配*(C++ no match for operator*)

编程入门 行业动态 更新时间:2024-10-25 20:27:06
C ++与运营商不匹配*(C++ no match for operator*)

我想重载运算符:

static Vector operator*(float s, Vector right){ Vector result(right.getX()*s, right.getY()*s, right.getZ()*s); return result; }

当我想使用它时:

Vector a(0,1,5) Vector v(4*a);

我有:

error: no match for 'operator*' (operand types are 'int' and 'Vector')

哪里不对?

I want to overload operator:

static Vector operator*(float s, Vector right){ Vector result(right.getX()*s, right.getY()*s, right.getZ()*s); return result; }

When I want to use it:

Vector a(0,1,5) Vector v(4*a);

I got:

error: no match for 'operator*' (operand types are 'int' and 'Vector')

What is wrong?

最满意答案

你需要声明(在类声明中)operator *作为非静态非成员和朋友,如:

friend Vector operator*(float s, Vector right);

并定义为(外部类声明):

Vector operator*(float s, Vector right){ return Vector(right.getX()*s, right.getY()*s, right.getZ()*s); }

Operator *在此处用作二元运算符。 如果你作为成员,那么第一个参数被隐式地当作当前对象(*适用于*,例如,如果你使用x * y,那么operator *适用于成员的x)。 但是,对于非成员,两个参数都可以是非Vector类型,并且可以根据需要转换为Vector。 如果您作为非成员非朋友和静态(在外部类声明中定义),这甚至可以工作

You need to declare (within class declaration) operator* as non-static non-member and friend like:

friend Vector operator*(float s, Vector right);

and define as (outside class declaration):

Vector operator*(float s, Vector right){ return Vector(right.getX()*s, right.getY()*s, right.getZ()*s); }

Operator * is used as binary operator here. If you make as member, then first argument is implicitly taken as the current object (on which * applies, for example, if you use x * y, then operator * applies on x for member). However, for non-member both the arguments can be non-Vector type and can be converted to Vector if needed. This will even work if you make as non-member non-friend and as static (tobe defined outside class declaration)

更多推荐

本文发布于:2023-07-24 00:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239305.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运营商   不匹配   operator   match

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!