Operator[][] overload

前端 未结 18 1867
轮回少年
轮回少年 2020-11-22 05:46

Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

If it is pos

18条回答
  •  误落风尘
    2020-11-22 06:27

    One approach is using std::pair:

    class Array2D
    {
        int** m_p2dArray;
    public:
        int operator[](const std::pair& Index)
        {
           return m_p2dArray[Index.first][Index.second];
        }
    };
    
    int main()
    {
        Array2D theArray;
        pair theIndex(2,3);
        int nValue;
        nValue = theArray[theIndex];
    }
    

    Of course, you may typedef the pair

提交回复
热议问题