Overloading operations

I've run into a slight problem with this bit of code I'm writing.
1
2
3
4
5
6
7
8
9
10
11
   cout << "\nTest " << test++ << ": Subscripting\n" << endl;

   const Vector3 v5(3.2, -5.4, 5.6);
   Vector3 v6(1.3, 2.4, -3.1);

   cout << "v5: " << v5 << endl;
   cout << "v6: " << v6 << endl;

   cout << "v5[0] = " << v5[0] << endl;
   cout << "v5[1] = " << v5[1] << endl;
   cout << "v5[2] = " << v5[2] << endl;


1
2
3
4
5
6
7
8
9
10
11
12

Vector3::Vector3(float x, float y, float z)
	{
	vectorArray[0] = x;
	vectorArray[1] = y;
	vectorArray[2] = z;
	}
	
float& Vector3::operator[](int i)
	{
	return vectorArray[i];
	}


When I try and compile my program. It keeps saying float Vector3::operator[](int) <near match> as my error. Is there anyway I can fix this in the operation it self other than going to the base code I'm suppose to use and remove const in this line const Vector3 v5(3.2, -5.4, 5.6);
Well for a start where on earth is "vectorArray" coming from, there's no declaration for this variable so you cannot return it.
Also I would recommend adding a couple of if statements to make sure you don't access an out of bounds element (once you've declared the element in the first place).
What does mean this text "float Vector3::operator[](int) <near match>"?! Could you be less stupid and show us the full error message?!

As for the problem operator [] defined in the class can be called only for non-const objects of the class. That to call the operator [] for const objects it should be overloaded in the class for example the following way

1
2
3
4
float Vector3::operator[](int i) const
{
   return vectorArray[i];
}

Last edited on
Topic archived. No new replies allowed.