gpt4 book ai didi

c++ - boost库中的矩阵赋值如何与括号一起使用?

转载 作者:搜寻专家 更新时间:2023-10-31 02:06:48 24 4
gpt4 key购买 nike

来自 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;
}

我对 m (i, j) = 3 * i + j; 感到困惑,因为 m 是一个对象,唯一将类和参数结合在一起的情况是构造函数,但在那里,它显然不是。

我是 C++ 的初学者。然而,与 Ruby 不同的是,C++ 中的技巧很少。

为了对C++有更深的探索,有没有哪位大神能从原理上给我解释一下?

最佳答案

在 C++ 中,您可以定义自己的运算符(并在需要时覆盖它们)。一种流行的访问器运算符是 []。但是,对于自定义运算符,() 也是可能的。

如果你看一下 matrix.hpp 的源代码来自 Boost,其中定义了 matrix 对象,确实有一个运算符 ()

/** 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_)];
}

/** 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

Boost 机制的较低级别实现乍一看可能有点复杂,但它之所以具有这样的语法,是因为定义中存在 operator ()

您可以查看有关运算符的更简单示例,例如 there (在 cppreference 上)。

关于c++ - boost库中的矩阵赋值如何与括号一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714040/

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