Operators for 3D Vector Mathematics
I'm writing a graphics program that uses 3D vectors, I have an existing library that I've written that already contains all the code for vector manipiulation but it was written in C using a struct to define a vector and funtions to manipulate them.
I now have a Vector class as I'm writing in C++ and rather than have to call a funtion which makes the code less readable I'd like to overload the operators, the only problem is I dont know how to write the function headers for the operator overloading for what I need or if its possable for some of it. this is whats needed
Vector + Vector = Vector
Vector - Vector = Vector
Vector x Vector = Vector (Cross product)
Vector . Vector = float (Dot product)
Vector * float = Vector (Scaling)
Vector = Vector
also if I'm using pointers to the vector class would I need to dereference the pointer to use the operators?
I'm not to sure how operator over loading works but would a line like this
Code:
CVector operator + (CVector &v2)
be processed as
Code:
return type = this + v2
Re: Operators for 3D Vector Mathematics
Quote:
Originally posted by Anarchist
also if I'm using pointers to the vector class would I need to dereference the pointer to use the operators?
yup, that's about right. use references when you can though. for instance:
CVector *myptr;
//some stuff to get the pointer
CVector & alias = *myptr;
something = alias + blah;
since you have alias as a reference instead of a pointer you can use the thing without dereferencing explicitly.
of course you could always do a bunch of other things...
myptr->operator+() can be called
(*myptr) + blah //you already knew that.
Same subject Different problem
when compiling my code I get the error
Quote:
error C2679: binary '*' : no operator defined which takes a right-hand operand of type 'const float' (or there is no acceptable conversion)
the 1 line of code that causes this is infact the second line that uses vector scaling
Code:
*polyNormal=( (*Triangle->GetVertex(FIRST)->GetNormal()) * (1-(alpha+beta)) )+
((*Triangle->GetVertex(SECOND)->GetNormal()) * alpha )+
((*Triangle->GetVertex(THIRD)->GetNormal()) * beta);
this basically boils down to vector= (vector * float) +(vector * float) +(vector * float)
at first glance you'd think I havnt written the code for the operator but an earlier line that uses it compiles fine
Code:
*position = *m_Start + (*m_Direction * t);
this being Vector = Vector + (Vector * float)
I can't see why these lines of code should be treated differently
could the problem be because I use function calls to get a pointer to the Vector(GetNormal) and then dereference this?
Interestingly enough if I replace the 1-(alpha+beta) with a variable of type float it works, could anyone explain this behaviour?
if it helps the operator for scaling id defined as
Code:
CVector operator * (float &val); //scale