geeksforgeeks-065-重载数组索引操作符

  1. 当需要检查索引是否越界时,重载[]可能会非常有用。
  2. 函数必须返回引用,因为类似“arr[i]”的表达式可能是lvalue。

如下程序演示了重载索引操作符[]:

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#include<iostream>
#include<cstdlib>

using namespace std;

// A class to represent an integer array
class Array
{
private:
int *ptr;
int size;
public:
Array(int *, int);

// Overloading [] operator to access elements in array style
int &operator[] (int);

// Utility function to print contents
void () const;
};


// Implementation of [] operator. This function must return a
// refernce as array element can be put on left side
int &Array::operator[](int index)
{
if (index >= size)
{
cout << "Array index out of bound, exiting";
exit(0);
}
return ptr[index];
}

// constructor for array class
Array::Array(int *p = NULL, int s = 0)
{
size = s;
ptr = NULL;
if (s != 0)
{
ptr = new int[s];
for (int i = 0; i < s; i++)
ptr[i] = p[i];
}
}

void Array::print() const
{
for(int i = 0; i < size; i++)
cout<<ptr[i]<<" ";
cout<<endl;
}

// Driver program to test above methods
int main()
{
int a[] = {1, 2, 4, 5};
Array arr1(a, 4);
arr1[2] = 6;
arr1.print();
arr1[8] = 6;
return 0;
}

Output:

1
2
1 2 6 5
Array index out of bound, exiting