overloading [][] operators in c++

后端 未结 5 1368
小蘑菇
小蘑菇 2020-12-11 11:39

I\'m writing a matrix 3x3 class in c++.

glm::mat3 provides access to matrix data through the [][] operator syntax.
e.g. myMatrix[0][0] = 1.0f;

5条回答
  •  一个人的身影
    2020-12-11 11:49

    There is no operator [][], so you need to overload the [] operator twice: once on the matrix, returning a surrogate object for the row, and once for the returned surrogate row:

    // Matrix's operator[]
    const row_proxy operator[](int row) const
    {
        return row_proxy(this, row);
    }
    // Proxy's operator[]
    const real operator[](int col) const
    {
        // Proxy stores a pointer to matrix and the row passed into the first [] operator
        return ((this->row >= 0 && this->row <= 2) && (col >= 0 && col <= 2)) ? this->matrix->_data[this->row][col] : 0.0f;
    }
    

提交回复
热议问题