• Advertisement
Sign in to follow this  

Conversion operators (C++)

This topic is 4209 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
As the above poster mentioned, you would have to create an implicit constructor for creating a matrix from a vector.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement