您的位置:首页 > 编程语言 > C语言/C++

C++运算符重载(12) - 重载数组索引操作符[]

2015-05-27 00:15 225 查看
本篇主要讨论索引操作符[]的重载。

下面是关于重载[]的一些注意事项:

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 Array::print() const
{
for(int i = 0; i < size; i++)
cout<<ptr[i]<<" ";
cout<<endl;
}

int main()
{
int a[] = {1, 2, 4, 5};
Array arr1(a, 4);
arr1[2] = 6;
arr1.print();
arr1[8] = 6;
return 0;
}
输出:

1 2 6 5

Array index out of bound, exiting
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: