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:


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?

I think this is what u meant?? Sorry if it's not and sorry for using double instead of float if it is correct.

#include <assert.h>
#include <iostream>

using namespace std;

class Vector3D
		double X, Y, Z;
		Vector3D() : X(0), Y(0), Z(0) {}
		Vector3D(double X_, double Y_, double Z_) : X(X_), Y(Y_), Z(Z_) {}
		~Vector3D() {}
		double& operator [](int Index)
			assert(Index >= 0 && Index <= 2);
			if (Index = 0)
				return X;
			else if (Index = 1)
				return Y;
			else if (Index = 2)
				return Z;
                //const overload here..


int main()
	Vector3D MyVec(3.2, -5.4, 5.6);

	return 0;

No, not exactly. My original post wasn't descriptive enough I think. Let me add more details.

I'm trying to overload a subscripting operator so that it can provide access to a value of a vector. It's the last part of the program that I cannot get right. It keeps returns wrong values (1.4013e-45, 4.58925e-41,0) instead of (3.2, -5.4, 5.6). I'm not really sure how to properly implement this part of it. The entire code is located here here and I've commented on the relevant parts.


Thanks for your help, I really appreciate it.

Uhh What I posted does exactly that :S

//Access the vectors and then cout<< the result.

cout<<MyVec[0];    //Prints 3.2
cout<<MyVec[1];    //Prints -5.4
cout<<MyVec[2];    //Prints 5.6

anything other than those 3 numbers [0], [1], [2].. Will produce an error.