技术交流QQ群:1027579432,欢迎你的加入!

1.C++中重载下标运算符[]

  • C++规定,下标运算符[]必须以成员函数的形式进行重载,该重载函数在类中的声明格式如下:
        返回值类型 & operator[] (参数列表);
        // 或者
        const 返回值类型 & operator[] (参数列表) const;
    
  • 使用第一种声明方式,[]不仅可以访问元素,还可以修改元素。使用第二种声明方式,[]只能访问而不能修改元素。在实际开发中,应该同时提供以上两种形式,这样做是为了适应const对象,因为通过const对象只能调用const成员函数,如果不提供第二种形式,那么将无法访问const 对象的任何元素。

2.实例如下

  • B是const对象,如果Array类没有提供const版本的operator[],那么cout << B[n-1] << endl; 将报错。虽然代码只是读取对象的数据,并没有试图修改对象,但是它调用了非const版本的operator[],编译器不管实际上有没有修改对象,只要是调用了非const的成员函数,编译器就认为会修改对象(至少有这种风险)。
        #include "iostream"
    
        using namespace std;
    
    
    
        class Array{
            public:
                Array(int len=0);
                ~Array();
            public:
                int & operator[] (int i);
                const int & operator[] (int i) const;
            public:
                int length() const{return m_len;}
                void show() const;
            private:
                int m_len;  // 数组长度
                int *m_p;  // 指向数组内存的指针m_p
        };
    
        // 构造函数定义 
        Array::Array(int len):m_len(len){
            if(len == 0)
                m_p = NULL;
            else
                m_p = new int[len];
        }
    
        Array::~Array(){
            delete[] m_p;
        }
        // 重载[]运算符
        int & Array::operator[] (int i){
            return m_p[i];
        }
    
        const int & Array::operator[] (int i) const{
            return m_p[i];
        }
    
        void Array::show() const{
            for(int i = 0; i < m_len; i++){
                if(i == m_len - 1)
                    cout << m_p[i] << endl;
                else    
                    cout << m_p[i] << " ";
            }
        }
    
        int main(){
            int n;
            cin >> n;
            Array A(n);
    
            for(int i = 0; i < A.length(); i++)
                A[i] = i * 5;
            A.show();
    
            const Array B(n);
            cout << B[n-1] << endl;  // 访问最后一个元素
            return 0;
        }