Index Operator Overload []

Why does it require you to be a member function of a class to work, and is it useful to return a link to a private member?

class X
{
public:

    int& operator[] (const size_t);
    const int &operator[] (const size_t) const;

private:
    static std::vector<int> data;
};

int v[] = {0, 1, 2, 3, 4, 5};
std::vector<int> X::data(v, v+6);

int& X::operator[] (const size_t index)
{
    return data[index];
}

const int& X::operator[] (const size_t index) const
{
    return data[index];
}
+3
source share
4 answers
  • What is the reason why [] is required as a member, you can read this question (sincerely). It seems to be as if this is really not a very convincing explanation.

  • How to return the link? Because you want to provide a way to not only read, but (for non-constant objects) to modify the data. If the return was not a link (or some proxy)

    v [i] = 4;

    does not work.

NTN

+3
source

It must be a member function according to 13.5.5:

Operator

[] - .

. , ( ).

data, , , ,

+2

, , , , .. :

T operator[]( const X &, size_t );

.

, , , , .

, , , , .

+2

What will be the syntax for calling a non-member operator[]? Any syntax for this would be inconvenient. operator[]takes one parameter within [and ]and is usually the index or data needed to search for an object.

Also, yes, it is a good idea to return the link, even if it is a private member. This is what STL vectors do, and just about any other class that I could think of that I have ever used, which provides operator[]. It would be recommended that it be supported.

-1
source

Source: https://habr.com/ru/post/1796292/


All Articles