gpt4 book ai didi

c++ - 在 C++ 中重载 [][] 运算符

转载 作者:太空狗 更新时间:2023-10-29 23:22:08 24 4
gpt4 key购买 nike

我正在用 C++ 编写矩阵 3x3 类。

glm::mat3 通过 [][] operator 语法提供对矩阵数据的访问。
例如myMatrix[0][0] = 1.0f; 会将第一行第一列条目设置为 1.0f

我想提供类似的访问权限。如何重载 [][] 运算符

我试过以下方法,但出现错误:

operator name must be declared as a function

const real operator[][](int row, int col) const
{
// should really throw an exception for out of bounds indices
return ((row >= 0 && row <= 2) && (col >= 0 && col <= 2)) ? _data[row][col] : 0.0f;
}

重载此运算符的正确方法是什么?

最佳答案

没有运算符[][],因此您需要重载[] 运算符两次:一次在矩阵上,返回一个surrogate。该行的对象,以及一次返回的代理项行:

// 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;
}

关于c++ - 在 C++ 中重载 [][] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com