I'm studying matrix operations, and out teacher provided us this 3 next functions:
//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);
}
I get that 'srcMatrix.at(i,j)' acts as a getter, that's pretty obvious, because the fucntions returns the value at that location. But I can't understand why it acts as a setter as well, there is no assignment. And which one of the 'at' functions is a getter and which is a setter?
The first member function float& mat3::at(int i, int j)
can be used as a setter. Because it returns a non-const
reference you can assign to it's result to change the matrix's elements.
For example srcMatrix.at(i,j) = 4.2;
will set the element that position to 4.2
.
The second overload const float& mat3::at(int i, int j) const
can only act as a getter. The result is a const
reference so it's not possible to assign to the result. Its provided so that it's still possible to get the value of an element if you have a const mat3
.