Operator[][] overload

前端 未结 18 2075
轮回少年
轮回少年 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:38

    You can use a proxy object, something like this:

    #include 
    
    struct Object
    {
        struct Proxy
        {
            Object *mObj;
            int mI;
    
            Proxy(Object *obj, int i)
            : mObj(obj), mI(i)
            {
            }
    
            int operator[](int j)
            {
                return mI * j;
            }
        };
    
        Proxy operator[](int i)
        {
            return Proxy(this, i);
        }
    };
    
    int main()
    {
        Object o;
        std::cout << o[2][3] << std::endl;
    }
    

提交回复
热议问题