我想重载运算符:
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)
更多推荐
发布评论