Reputation: 867
From this sample code from Boost official site:
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main () {
using namespace boost::numeric::ublas;
matrix<double> m (3, 3);
for (unsigned i = 0; i < m.size1 (); ++ i)
for (unsigned j = 0; j < m.size2 (); ++ j)
m (i, j) = 3 * i + j;
std::cout << m << std::endl;
}
I am confused with m (i, j) = 3 * i + j;
because m is a object and the only case that combines class and argument together is constructor function, but there, it is obviously not.
I am a beginner of C++. However, being different from Ruby there is few trick in C++.
In order to have a deep discovery toward C++, is there any who can give me a explanation in principle about that?
Upvotes: 1
Views: 718
Reputation: 5620
In C++, you can define your own operators (and override them if you need to). One popular operator for accessors is []
. However, ()
is possible as well for a custom operator.
If you take look at the source code of matrix.hpp from Boost, in which the matrix
object is defined, there is indeed an operator ()
.
/** Access a matrix element. Here we return a const reference
* \param i the first coordinate of the element. By default it's the row
* \param j the second coordinate of the element. By default it's the column
* \return a const reference to the element
*/
BOOST_UBLAS_INLINE
const_reference operator () (size_type i, size_type j) const {
return data () [layout_type::element (i, size1_, j, size2_)];
}
and
/** Access a matrix element. Here we return a reference
* \param i the first coordinate of the element. By default it's the row
* \param j the second coordinate of the element. By default it's the column
* \return a reference to the element
*/
BOOST_UBLAS_INLINE
reference operator () (size_type i, size_type j) {
return at_element (i, j);
}
// Element assignment
The lower level implementation of Boost mechanics might be a little complex to understand at the first look, but what allows it to have a syntax like this is the presence of operator ()
in the definition.
You can check simpler examples about operators, for example there (on cppreference).
Upvotes: 2