In order to call a function that overloads the "[]" operator, do I have to pass the subscript of an array of class objects? or can it be any type of array?
The code below is just some experiment I have been doing to understand overloading operators, but in lines 46 and 49 i have some trouble understanding (due to voodoo coding) what exactly is going on.
#include <iostream>
#include <cstdlib>
usingnamespace std;
class Plant
{
int *pointer;
int num_of_elements;
public:
Plant (int sub)
{
num_of_elements = sub;
pointer = newint [num_of_elements];
for (int n = 0; n < num_of_elements; n++)
{
pointer [n] = (n * 5);
}
}
int &operator [] (int sub)
{
if (sub < 0 || sub >= num_of_elements)
{
cout << "Error, no subscript found" << "\n";
exit(0);
}
elsereturn pointer[sub];
}
};
int main ()
{
Plant array(5);
for (int n = 0; n < 5 ; n++)
{
array[n] = (n * 2); //by the way, does the class object "array" get converted to an actual array in this statement?
}
cout << array[3]; //Can I only pass an array of class objects?
}