Operator[][] overload

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

    Using C++11 and the Standard Library you can make a very nice two-dimensional array in a single line of code:

    std::array, rowCount> myMatrix {0};
    
    std::array, rowCount> myStringMatrix;
    
    std::array, rowCount> myWidgetMatrix;
    

    By deciding the inner matrix represents rows, you access the matrix with an myMatrix[y][x] syntax:

    myMatrix[0][0] = 1;
    myMatrix[0][3] = 2;
    myMatrix[3][4] = 3;
    
    std::cout << myMatrix[3][4]; // outputs 3
    
    myStringMatrix[2][4] = "foo";
    myWidgetMatrix[1][5].doTheStuff();
    

    And you can use ranged-for for output:

    for (const auto &row : myMatrix) {
      for (const auto &elem : row) {
        std::cout << elem << " ";
      }
      std::cout << std::endl;
    }
    

    (Deciding the inner array represents columns would allow for an foo[x][y] syntax but you'd need to use clumsier for(;;) loops to display output.)

提交回复
热议问题