• Advertisement
Sign in to follow this  

C++: I need some help overloading an operator...

This topic is 3965 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

I'm creating a Quaternion class and I've overloaded the = operator to take a float pointer.
float i[] = {1, 0, 0, 0};
quaternion q;
q = i;

I cannot, however, do this:
float i[] = {1, 0, 0, 0};
quaternion q = i;

How do I overload this operator so I can use it upon initialization? Like the string class.

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Drunken_Monkey
How do I overload this operator so I can use it upon initialization?

You can't.

Quote:
Like the string class.

The string class does not do anything remotely like that.

The statement float i[] = {1, 2, 3, 4}; relies on the right-hand side of the statement being a literal expression, resolved at compile-time so that the compiler knows the dimensions (and type) of the object being assigned. That's how the following is legal and safe:
char c[] = "This is a constant-length string literal, whose data is hard-coded into the binary and which should not be lightly tampered with!";

You can, of course, overload your assignment operator to assign a value to a pointer to a float, but be aware that there are numerous little gotchas that may occur if you treat the literal and the runtime-generated result as identical objects.
const float * operator = () const
{
if(internal_float_array)
{
delete [] internal_float_array;
}

internal_float_array = new float[4];
internal_float_array[0] = x;
internal_float_array[1] = y;
internal_float_array[2] = z;
internal_float_array[3] = w;

return internal_float_array;
}

Do NOT modify the array returned by this operator. I know, I made it return a const pointer, but you know how you kids like to play with const_cast!

(This is how std::string::c_str() works, and why you should make a copy of that character array if you want to do anything fancy with it.)

Share this post


Link to post
Share on other sites
Quote:
Original post by Drunken_Monkey
How do I overload this operator so I can use it upon initialization? Like the string class.


Initialization does not use the assignment operator, it uses a constructor. Besides, if the constructor is non-implicit, you don't even need an assignment operator overload (since it will create a temporary quaternion and use the assignment function for quaternions).

class quaternion 
{
float value[4];
public:
quaternion(const float (&arr)[4])
{
std::copy(arr, arr+4, this->value);
}
};

Share this post


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

  • Advertisement