operator[][] C++

前端 未结 5 1397
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 16:24

I\'d like to overload operator[][] to give internal access to a 2D array of char in C++.

Right now I\'m only overloading operator[], which goes

5条回答
  •  孤街浪徒
    2021-02-15 17:04

    Don’t try to do that – as others have said, overloading operator [] the way you do actually provides the [][] syntax for free. But that’s not a good thing.

    On the contrary – it destroys the encapsulation and information hiding of your class by turning an implementation detail – the char* pointer – to the outside. In general, this is not advisable.

    A better method would be to implement an operator [,] which takes more than one argument, or indeed an operator [][]. But neither exists in C++.

    So the usual way of doing this is to ditch operator [] altogether for more than one dimension. The clean alternative is to use operator () instead because that operator can have more than one argument:

    class Object
    {
        char ** charMap ;
        char& operator ()(int row, int column)
        {
            return charMap[row][column];
        }
    };
    

    For more information, see the article in the C++ FAQ Lite.

提交回复
热议问题