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

本篇主要讨论索引操作符 [] 的重载。
下面是关于重载[]的一些注意事项:
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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值