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

C++:重载运算符避免数组越界

2016-02-21 14:34 501 查看

C++:重载运算符避免数组越界

标签: C++ 重载运算符 数组越界

by 小威威

我们知道,数组越界有时候会引发很危险的行为,然而编译器却不能检测出数组越界,那么,我们该如何预防这一危险的行为呢?

那就是重载[]运算符。

代码如下:

//
//  main.cpp
//  overload_operators[]
//
//  Created by apple on 16/2/21.
//  Copyright (c) 2016年 apple. All rights reserved.
//

# include <iostream>
# define SIZE 10

using namespace std;

class array_protect {
private:
int array[SIZE];
public:
array_protect () {
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
}
int& operator [](int i) {
if (i >= SIZE) {
cout << "The index is out of bound" << endl;
cout << "Return the first number of array" << endl;
cout << "a[0] = ";
return array[0];
}
return array[i];
}
};

int main(void) {
array_protect array;
cout << "array[2] = " << array[2] << endl;
cout << "array[10] = " << array[10] << endl;
cout << "array[13] = " << array[15] << endl;
return 0;
}

输出结果:
array[2] = 2
array[10] = The index is out of bound
Return the first number of array
a[0] = 0
array[13] = The index is out of bound
Return the first number of array
a[0] = 0


在重构的代码中,我们可以用一个if条件语句来排除数组越界的情况,这样可以尽量减少错误的情况,很好用!!!

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: