Hello everybody, I've got a question about overloading brackets.
I need to output the contents of an array, that I created and populated in the constructer of my class, using the [] operator, and I need "to overload the [] in the class."
Our instructions are,
"Write a class that creates and populates an array of integers (any size) using a pointer. Make sure the constructor initializes and populates the array. In your main program output the contents of an object of this class by using the [] operator. You will have to overload the [] in the class. Also, show that you cannot output an array element that is out of bounds."
So far, I've got:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
using namespace std;
class intArray
{
public:
intArray operator [] (intArray); //OVERLOADING [] OPERATOR
intArray(int *pA)
{
pA = new int[10];
int count, j;
j = 0;
for (count = 0; j < 10; j++)
{
pA[j] = 0;
}//end for
//POPULATE ARRAY:
int populate = 5;
for (count = 0; j < 10; j++)
{
pA[j] = populate;
populate++;
} //end 2nd for
} //end constructor definition
intArray () { };//"necessary cuz I 'explicitly'...
//...declared another constructor"
}; //end class
int main()
{
intArray mainArray(int *p);
cout << p[0] << endl;//This is the line I'm confused about...
return 0;
}
|
I know some post on here are desperate last munite attempts to get a program written for some required computer class, but I'm not here for that. CS is my major and I've just got an honest question. =]
Right now my understanding of overloading is so that you can use operators in a slightly different way than normal. So in my case, I guess that I'm using brackets differently because I'm outputting an array in a class constructor that I declared using pointers... I think...
As I commented on line 41 (the 4th-to last line) in my code, I'm stuck there. When I compile, I only get 1 error and it's on that line:
intArray.cpp: In function `int main()':
intArray.cpp:41: `p' undeclared (first use this function)
intArray.cpp:41: (Each undeclared identifier is reported only once for each
function it appears in.)
I know it seems like I'm only outputting the first cell of the array by writting p[0] but I just haven't written the rest of them yet, so I'm just doing p[0] for a test...
So, my big question is: How would I output the array for the object mainArray using the overloaded [] operator?