C++运算符重载(12) - 重载数组索引操作符[]
2015-05-27 00:15
225 查看
本篇主要讨论索引操作符[]的重载。
下面是关于重载[]的一些注意事项:
1) 当需要检测下标是否越界时,重载[]是很有用的。
2) 重载函数必须返回引用,因为类似的表达式“arr[i]”可以被当成一个左值。
下面程序演示了重载索引操作符[]
1 2 6 5
Array index out of bound, exiting
下面是关于重载[]的一些注意事项:
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
相关文章推荐
- 【C++深度剖析教程12】数组操作符的重载
- 第34课 数组操作符的重载
- 重载数组下标操作符,使用operator
- C++运算符重载(3) - 什么时候需要自定义赋值操作符
- 数组的操作符重载
- C++运算符重载(4) - 不能被重载的操作符
- c++操作符重载与友元函数 单目 双目 左移右移 ==号操作符重载 自定义数组
- c++操作符重载(数组类重载[]、=、==、!=操作符)
- C++运算符重载(6) - 转换操作符
- 数组与指针-下标索引操作符的交换性
- 第34课 数组操作符的重载
- 操作符的重载以及数组/vector对象的初始化
- 数组操作符的重载
- 数组操作符的重载
- php中重载数组操作符
- 读取数据到结构体数组(重载输入输出操作符)
- 【c++习题】【17/5/22】重载数组下标操作符
- 第三十四课:数组操作符的重载----------狄泰软件学院
- 第34课 - 数组操作符的重载
- C++运算符重载(4) .*和.->操作符介绍