这两个函数如何充当 getter 和 setter?
How does these 2 functions act as getters and setters?
我正在学习矩阵运算,老师给我们提供了接下来的三个函数:
//methods used as GETTERS and SETTERS - to access the matrix elements
float& mat3::at(int i, int j) {
return matrixData[i + 3 * j];
}
const float& mat3::at(int i, int j) const {
return matrixData[i + 3 * j];
}
mat3& mat3::operator =(const mat3& srcMatrix) {
//usage example for the "at" getter/setter methods
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//at(i,j) acts as a setter
//srcMatrix.at(i, j) is used as a getter
at(i, j) = srcMatrix.at(i, j);
}
}
return (*this);
}
我知道 'srcMatrix.at(i,j)' 充当 getter,这很明显,因为函数 returns 是那个位置的值。但是我不明白为什么它也充当 setter ,没有分配。 'at' 函数中哪个是 getter,哪个是 setter?
第一个成员函数float& mat3::at(int i, int j)
可以作为setter使用。因为它 returns 是一个非 const
引用,您可以将其分配给它的结果以更改矩阵的元素。
例如 srcMatrix.at(i,j) = 4.2;
会将位置为 4.2
的元素设置为
第二个重载 const float& mat3::at(int i, int j) const
只能充当 getter。结果是一个 const
引用,因此无法分配给结果。提供它是为了在您有 const mat3
.
时仍然可以获取元素的值
我正在学习矩阵运算,老师给我们提供了接下来的三个函数:
//methods used as GETTERS and SETTERS - to access the matrix elements
float& mat3::at(int i, int j) {
return matrixData[i + 3 * j];
}
const float& mat3::at(int i, int j) const {
return matrixData[i + 3 * j];
}
mat3& mat3::operator =(const mat3& srcMatrix) {
//usage example for the "at" getter/setter methods
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//at(i,j) acts as a setter
//srcMatrix.at(i, j) is used as a getter
at(i, j) = srcMatrix.at(i, j);
}
}
return (*this);
}
我知道 'srcMatrix.at(i,j)' 充当 getter,这很明显,因为函数 returns 是那个位置的值。但是我不明白为什么它也充当 setter ,没有分配。 'at' 函数中哪个是 getter,哪个是 setter?
第一个成员函数float& mat3::at(int i, int j)
可以作为setter使用。因为它 returns 是一个非 const
引用,您可以将其分配给它的结果以更改矩阵的元素。
例如 srcMatrix.at(i,j) = 4.2;
会将位置为 4.2
的元素设置为
第二个重载 const float& mat3::at(int i, int j) const
只能充当 getter。结果是一个 const
引用,因此无法分配给结果。提供它是为了在您有 const mat3
.