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

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条件语句来排除数组越界的情况,这样可以尽量减少错误的情况,很好用!!!


以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值