Overload operator[] function trouble

Hi i am having trouble writing this function:
int& ArrayVector::operator[](int index)
It must do the following
Return reference to index-th element of the array
// If index is greater or equal to size of the array,
// 1. expand the array to cover up to (index+1)
// elements
// 2. copy elements from old array to expanded array
// 3. fill 0 for elements from n-th to (index-1)-th
// 4. return the index-th element
// Also keep track the size of the array
Here is my class so far. I only need help with this function. Thanks!!

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
class ArrayVector {
private:
  int* data;
  int n;

public:
  ArrayVector() : data(NULL), n(0) { }

  int size() const {
    return n;
  }

  // print content of the array separated by “ “
  void print() {
    if (n == 0)
      return;

    // print from first element to second last element
    for (int i = 0; i < n-1; ++i)
      cout << data[i] << " ";

    // print last element
    cout << data[n-1] << endl;
  }

  // Return reference to index-th element of the array
  //  If index is greater or equal to size of the array,
  //    1. expand the array to cover up to (index+1) 
  //  	elements
  //    2. copy elements from old array to expanded array
  //    3. fill 0 for elements from n-th to (index-1)-th
  //    4. return the index-th element
  //  Also keep track the size of the array

  int& operator[](const int index);

};
 


int& ArrayVector::operator[](int index) {
Last edited on
Topic archived. No new replies allowed.