Operator[][] overload

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

    Sample code:

    template
    class Array2D
    {
    public:
        Array2D(int a, int b)  
        {
            num1 = (T**)new int [a*sizeof(int*)];
            for(int i = 0; i < a; i++)
                num1[i] = new int [b*sizeof(int)];
    
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < b; j++) {
                    num1[i][j] = i*j;
                }
            }
        }
        class Array1D
        {
        public:
            Array1D(int* a):temp(a) {}
            T& operator[](int a)
            {
                return temp[a];
            }
            T* temp;
        };
    
        T** num1;
        Array1D operator[] (int a)
        {
            return Array1D(num1[a]);
        }
    };
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        Array2D arr(20, 30);
    
        std::cout << arr[2][3];
        getchar();
        return 0;
    }
    

提交回复
热议问题