Detailed explanation of C++ subscript operator

C++ stipulates that the subscript operator [ ]must be overloaded as a member function. The declaration format of this overloaded function in the class is as follows:

返回值类型 & operator[ ] (参数);

const return value type& operator[ ] (parameter) const;

Using the first declaration method, [ ]you can not only access the element, but also modify it. Using the second declaration method, [ ]the element can only be accessed but not modified. In actual development, we should provide the above two forms at the same time. This is done to adapt to const objects, because only const member functions can be called through const objects. If the second form is not provided, then any element of the const object will not be accessible. . Below we use a specific example to demonstrate how to overload [ ]. We know that some older compilers do not support variable-length arrays, such as VC6.0, VS2010, etc., which sometimes brings inconvenience to programming. Below we implement variable-length arrays through a custom Array class.

    #include <iostream>
    using namespace std;
    class Array{
    public:
        Array(int length = 0);
        ~Array();
    public:
        int & operator[](int i);
        const int & operator[](int i) const;
    publ

Guess you like

Origin blog.csdn.net/shiwei0813/article/details/132891412