[C++ Operator Overloading] Explore the subscript operator [] overloading in C++


Exploring subscript operator overloading in C++

introduction

In C++ programming, operator overloading is a very powerful feature that allows us to extend or customize the language's operators in a natural way. Among them, the subscript operator []is an important operator commonly used in arrays and container classes. This article will delve into how to overload the subscript operator in C++ [], as well as the inner logic and application scenarios of doing so.

As Bjarne Stroustrup said in "The C++ Programming Language": "C++'s operator overloading allows programmers to create more natural and easier-to-understand code."

What is the subscript operator[]?

The subscript operator (Subscript Operator) []is mainly used in C++ to access elements in an array or container. For example, arr[2]means accessing arrthe third element of the array named.

Why do you need to overload the subscript operator?

Overloading the Subscript Operator is mainly used for custom data structures, such as lists, queues, stacks, etc., to provide a more natural way of accessing elements. This way, we can use these data structures just like built-in arrays.

How to overload the subscript operator?

basic grammar

The basic syntax for subscript operator overloading is as follows:

T& operator[](const int index);

Among them, Tis the type of the returned element and indexis the index of the element to be accessed.


//1.使用这种声明方式,[ ]不仅可以访问元素,还可以修改元素。
返回值类型 & operator[ ] (参数);
//2.使用这种声明方式,[ ]只能访问而不能修改元素。
const 返回值类型 & operator[ ] (参数) const;


code example

Below is a simple IntListclass that overloads the subscript operator [].

#include <iostream>
#include <vector>

class IntList {
    
    
private:
    std::vector<int> list;
public:
    IntList(std::vector<int> l) : list(l) {
    
    }
    
    // 重载下标运算符
    int& operator[](const int index) {
    
    
        return list.at(index);
    }
};

int main() {
    
    
    IntList myList({
    
    1, 2, 3, 4, 5});
    std::cout << myList[2];  // 输出3
    return 0;
}

In this example we use std::vectoras the underlying data structure. operator[]The function returns a reference to the element at the specified index.

In the source code of the GCC compiler, std::vectorthe subscript operator overloading is implemented in the class <vector>of the header file ._Vector_base


#include <iostream>
using namespace std;

class Array{
    
    
public:
    Array(int length = 0);
    ~Array();
public:
    int & operator[](int i);
    const int & operator[](int i) const;
public:
    int length() const {
    
     return m_length; }
    void display() const;
private:
    int m_length;  //数组长度
    int *m_p;  //指向数组内存的指针
};

Array::Array(int length): m_length(length){
    
    
    if(length == 0){
    
    
        m_p = NULL;
    }else{
    
    
        m_p = new int[length];
    }
}

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::display() const{
    
    
    for(int i = 0; i < m_length; i++){
    
    
        if(i == m_length - 1){
    
    
            cout<<m_p[i]<<endl;
        }else{
    
    
            cout<<m_p[i]<<", ";
        }
    }
}

int main(){
    
    
    int n;
    cin>>n;

    Array A(n);
    for(int i = 0, len = A.length(); i < len; i++){
    
    
        A[i] = i * 5;
    }
    A.display();

    const Array B(n);
    cout<<B[n-1]<<endl;  //访问最后一个元素

    return 0;
}
//重载[ ]运算符以后,表达式arr[i]会被转换为:
arr.operator[ ](i);


Considerations and best practices

  1. Return type : Generally, the subscript operator should return a reference to the element to support assignment operations.
  2. Exception handling : Index out-of-bounds situations should be considered and handled appropriately.
  3. Constant overloading : To support constant objects, a version that returns a constant reference should be provided operator[].

Summarize

Overloading the subscript operator not only provides a natural way to access elements in a custom data structure, but also increases the readability and maintainability of your code. When we deeply understand the working principle of this operator, we will find that it is actually a language-level abstraction. This abstraction allows us to express the operation and access of data more freely, thus getting closer to human intuition. thinking.

As Bjarne Stroustrup said in "The C++ Programming Language": "Abstraction is a powerful tool we use to understand complex systems."

I hope this article can help you deeply understand the subscript operator overloading in C++ and use it flexibly in actual programming.

Conclusion

In our programming learning journey, understanding is an important step for us to move to a higher level. However, mastering new skills and ideas always requires time and persistence. From a psychological point of view, learning is often accompanied by constant trial and error and adjustment, which is like our brain gradually optimizing its "algorithm" for solving problems.

This is why when we encounter mistakes, we should view them as opportunities to learn and improve, not just as annoyances. By understanding and solving these problems, we can not only fix the current code, but also improve our programming skills and prevent making the same mistakes in future projects.

I encourage everyone to actively participate and continuously improve their programming skills. Whether you are a beginner or an experienced developer, I hope my blog will be helpful on your learning journey. If you find this article useful, you may wish to click to bookmark it, or leave your comments to share your insights and experiences. You are also welcome to make suggestions and questions about the content of my blog. Every like, comment, share and attention is the greatest support for me and the motivation for me to continue sharing and creating.


Read my CSDN homepage and unlock more exciting content: Bubble’s CSDN homepage
Insert image description here

Guess you like

Origin blog.csdn.net/qq_21438461/article/details/132947260