Hello,
I'm trying to overload an indexing operator and I'm running into issues with a vector (3 dimensions). Here is what it should do:
operator[]
The indexing operator should be overloaded to provide accessor methods for the class. Subscript 0 should provide access to the x component value of the vector; subscript 1 to the y component and subscript 2 to the z component. Subscript values other than 0, 1, or 2 produce undefined results. For speed, no error checking needs to be done.
The choice of how the data members are implemented in the class could greatly affect the complexity of overloading this particular operator.
Don't forget that this operator needs to be overloaded twice, once for getting a value and once for setting a value.
This is what I tried:
In class under private...
float operator[](int index) const;
float & operator [] (int index);
In the .cpp file
float Vector3::operator [] (int index) const
{
return coord[index];
}
float & Vector3::operator [] (int index)
{
return coord[index];
}
But when I run the program and cout the vector I get the following values:
v5: (3.2, -5.4, 5.6)
v5[0] = 1.4013e-45
v5[1] = 4.55786e-41
v5[2] = 0
Where 0, 1, and 2 should be the values 3.2, -5.4, and 5.6 accordingly. What am I doing wrong?