简体   繁体   中英

How to overload operator [ ] in C++?

I have some problems for overloading the operator [] in C++ for a matrix.Let's say that in my Class Matrix I have a 2X2 matrix m[2][2] .What the code should look like if I want to call an element from the array m[1][1] instead of object.m[1][1] ? I guess the header should be something like int operator[] (const int) but I don't know how to build it...If someone can help me thanks in advance.

There are two solutions. First, as @chris suggests, you can use operator()( int i, int j ) ; a lot of mathematically oriented people even prefer this. Otherwise, operator[] has to return a proxy; a type on which [] is also defined, to which the second [] can be applied to return the correct results. For two dimensional structures, the simplest proxy is just a pointer to the row, since [] is defined for pointers. But it's often preferable to return a full class type, in order to do error checking. Something like:

template <typename T>
Matrix2D
{
    int myRowCount;
    int myColumnCount;
    std::vector<T> myData;
public:
    T& getRef( int i, int j )
    {
        return myData[ i * myRowCount +  j ];
    }

    class Proxy
    {
        Matrix2D* myOwner;
        int myRowIndex;
    public:
        Proxy( Matrix2D* owner, int i )
            : myOwner( owner )
            , myRowIndex( i )
        {
        }

        T& operator[]( int j )
        {
            return myOwner->getRef( myRowIndex, j );
        }
    };

    Proxy operator[]( int i )
    {
        return Proxy( this, i );
    }
};

You'll probably want a const version of the Proxy as well, in order to overload [] on const.

For the () version, just replace getRef with operator() (literally), and drop the Proxy and the operator[] .

Here is an example how operator [] can be implemented for a class that has a two-dimensional array Try it and you will be satisfied.:)

You will need neither a proxy nor a compound operator function.

#include <iostream>

int main()
{
    struct A
    {
        int a[10][10];
        int ( & operator []( int n ) )[10]
        {
            return ( a[n] );
        }
    };

    A a;

    for ( int i = 0; i < 10; i++ )
    {
        for ( int j = 0; j < 10; j++ )
        {
            a[i][j] = 10 * i + j;
        }
    }

    for ( int i = 0; i < 10; i++ )
    {
        for ( int j = 0; j < 10; j++ )
        {
            std::cout << a.a[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM