Skip to main content
gamedev.net
🔒 Locked 🎮 Unity

Conversion operators (C++)

Started by Kustaz Aug 11, 2006 at 3:25 AM 3 replies 700+ views
Original Post
Kustaz
Kustaz
Hi there everybody, I recently wrote a matrix class (As in, the mathematical tool), which works perfectly for all my matrix needs. I want to write a vector class based on the matrix class, but with a few more bells and whistles specific to vectors. The problem is, I want to avoid rewriting code for things such as multiplication of vectors, subtraction, scalar multiplication, because these are identical to matrices. I figured I could do this by providing a conversion operator to a Matrix type. This would allow me to write:


VectorA = VectorA * VectorB;



However, when compiling, I recieve the following error: error C2676: binary '*' : 'Math::Vector3<_Real>' does not define this operator or a conversion to a type acceptable to the predefined operator Despite providing the following conversion operator inside Vector3:

//_mData is a member of Vector3, of type matrix, and does support binary *
operator Math::Matrix<_Real>()
{
    return _mData;
};



What am I doing wrong? Is this sort of thing even possible? And is there a better way to go about this? Thanks in advance.
Aardvajk
Aardvajk
Don't know if this will help, but I've just compiled the following:

#include <stdio.h> // at work and don't have the STL :(class x{public:    x(int v) : val(v) { }    int val;};x operator*(x a,x b){   return x(a.val*b.val);}class y{public:    y(x v) : val(v) { }    operator x(){ return val; }    x val;};void main(){    y a(2),b(2);    y c=a*b;    printf("%d\n",c.val);}


and it compiled, ran and produced the output "4" as expected.
ToohrVyk
ToohrVyk
As the above poster mentioned, you would have to create an implicit constructor for creating a matrix from a vector.
moeron
moeron
Isn't it a bit wasteful to create a temporary matrix everytime you want to do vector operations? It seems a bit backwards - wouldn't some matrix operations be done as a series of vector ops as opposed to the other way around?
moe.ron
joanusdmentia
joanusdmentia
Quote:
Original post by ToohrVyk
As the above poster mentioned, you would have to create an implicit constructor for creating a matrix from a vector.


The other way around actually. The operator*() will be returning a Matrix, which the OP's then assigning to a Vector.
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The nly verdict is vengeance; a vendett o

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.