本篇主要讨论索引操作符 [] 的重载。
下面是关于重载[]的一些注意事项:
1) 当需要检测下标是否越界时,重载[]是很有用的。
2) 重载函数必须返回引用,因为类似的表达式“arr[i]”可以被当成一个左值。
下面程序演示了重载索引操作符[]
// 数组类的重载操作
#include<iostream>
#include<cstdlib>
using namespace std;
// 数组类
class Array {
private:
int* ptr;
int size;
public:
Array(int*, int);
// 重载[]操作符,使得可以像数组一样访问这个类
int& operator[] (int);
void print() const;
};
// []操作符的重载实现。这个函数必须返回引用,且不能为const,因为可能会用作左值。例如arr[] = xxx;
int& Array::operator[](int index) {
if (index >= size) {
cout << "Array index out of bound, exiting";
exit(0);
}
return ptr[index];
}
// 构造函数
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 Ar