operator[][] C++

前端 未结 5 1408
佛祖请我去吃肉
佛祖请我去吃肉 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:02

    There is no [][] operator. What actually happens is that the second [] operates on the variable returned by the first []. Because there is already that functionality, it would create ambiguity were there to exist a [][] operator.


    For example: let's say you have a variable x of some type T.

    T x = new T();
    

    If we use the [] operator, let's say a variable of other type Q is returned:

    Q y = x[0];
    

    And then using the [] operator on a variable of type Q might return a variable of type R:

    R z = y[0];
    

    Therefore x[][] returns a variable of t ype R.

    Let's say we actually were able to overload [][] for type T such that it returned a type S:

    S a = x[0][0];
    

    The compiler would have no way of knowing if it should use the [][] operator on x to return a type S variable, or use the [] operator twice in a row to return a type R variable. This is the ambiguity I mentioned above.


    Your best bet if you're stuck on using square brackets is to have operator[] return a variable which also has [] overloaded (or perhaps a variable of the same type, with a flag set), and have that initially returned variable deal with the second [].

    But the best solution here (as mentioned already in another answer) is to use a different operator such as ().

提交回复
热议问题