I've been doing work with 3D vectors, and so I decided to overload the +,-, and * operators to make basic algebra operations more intuitive to program with. I've succeeded with accurate results but I have a question about overloading * to denote multipliying a vector by a scalar. Precedence and associativity work for multiplication by a scalar, as they do for the regular * operator.
The nearly identical declaration, aside from order of the arguments was the only way I could figure out to allow me type either:Code:class Vect{ private: public: unsigned dimension; float x; float y; float z; }; Vect operator*(float scalar, Vect the_vect){ int i=0; Vect scalar_product; scalar_product.x = scalar*(the_vect.x); scalar_product.y = scalar*(the_vect.y); scalar_product.z = scalar*(the_vect.z); return scalar_product; } Vect operator*( Vect the_vect, float scalar){ int i=0; Vect scalar_product; scalar_product.x = scalar*(the_vect.x); scalar_product.y = scalar*(the_vect.y); scalar_product.z = scalar*(the_vect.z); return scalar_product; }
ORCode:vect1 = 7.15*vect1;
Is there another way to overload the * operator once and to request it to disregard the order of the arguments? This didn't come up with + or - because the arguments for those were both of type Vect, whereas here I've got a float and my Vect type.Code:vect1 = vect1*7.15;
Any thoughts?



3Likes
LinkBack URL
About LinkBacks



