Class operators

20 May 2010 . Edited: 20 May 2010

I would do a search for this, but I can't seem to phrase it to get google to do my bidding.

I have a quaternion class that contains the standard 4 scalars as variables. This class has an operator:

//Quaternion multiplication
QUATERNION QUATERNION::operator* (QUATERNION multiplier) {
QUATERNION temp;
temp.h = h*multiplier.h - i*multiplier.i - j*multiplier.j- k*multiplier.k;
temp.i = i*multiplier.h + h*multiplier.i + j*multiplier.k - k*multiplier.j;
temp.j = h*multiplier.j - i*multiplier.k + j*multiplier.h + k*multiplier.i;
temp.k = h*multiplier.k + i*multiplier.j - j*multiplier.i + k*multiplier.h;
return (temp);
}

This works when multiplying two quaternions. Is there a way to create it do that I can know when I'm multiplying by a quaternion, or by a scalar (double) and handle it appropriately? The operation would just be multiplying each component by that scalar.

A simple point towards what this is called would help.

20 May 2010 . Edited: 20 May 2010

I think all you need to do is define the operator again but use double as the arguement so in your class you would have:-

class QUATERNION {

QUATERNION operator* (double multiplier);
QUATERNION operator* (QUATERNION multiplier);

};

QUATERNION QUATERNION::operator* (QUATERNION multiplier) {
...
}

QUATERNION QUATERNION::operator* (double multiplier) {
...
}

(replacing ... with code).

The compiler will then just choose the appropriate form depending on the multiplier used in an expression in your code. This is a result of normal c++ function overloading where the label and return type of the function is the same but the signature (parameters) are different.

Hope that helps,

Richard.