2D & 3D vector operators

Started by
12 comments, last by Ravyne 16 years, 10 months ago
As long as you are clear what they do, using operators is ok. true, * is also used sometimes for vector scaling, but scaling is usually achieved through the use of matrices. Best is to use names, like scale(), dot() and cross(). You also have to decide if the operators return by value (accessor) or by reference (modifier). I'd stick with accessors, and return by value.

Vector scale(const Vector& other) const { return Vector(x*other.x, y*other.y, z*other.z); }

the operator == or != have some significance, but you might as well use a function.

bool isEqual(const Vector& other, float threshold=1.0E-6) const { ... }

Everything is better with Metal.

Advertisement
Quote:Original post by oliii
You also have to decide if the operators return by value (accessor) or by reference (modifier). I'd stick with accessors, and return by value.

Vector scale(const Vector& other) const { return Vector(x*other.x, y*other.y, z*other.z); }



We have that discussion at work too, we decided to go this way:

vector.Scale(vector); modifies the operated vector and returns a reference
vector.Scaled(vector) const; does not modify and returns a new value

This discussion arised with the normalize method... we difference between normalize and normalized



At work we use functions like Inverse() and Inverse_In_Place(), Normalize() and Normalize_In_Place(), etc., so there's no ambiguity at all between accessors and modifiers. My personal library just uses accessors everywhere, but that's just me.
When overloading operators what you really want to pay attention to is operator precedence. For example, the "^" operator has a lower precedence than the "*" operator, if you overload them for the Cross Product and the Dot Product respectively, does this preserve the natural execution order one would expect?

Before you even get to that stage however, you need to make sure that the overload is natural and unambiguous, meaning that the operation performed is the first and only interpretation of that operator that comes to mind, or at least is the predominant interpretation by a wide margin.


I used to be in the camp that supported the more terse "overload the operators" camp, but have since realized the problems therein, so I changed much of my math classes.

throw table_exception("(? ???)? ? ???");

This topic is closed to new replies.

Advertisement