【问题标题】:How can matrix assignment in boost library work with parenthesis?boost库中的矩阵分配如何与括号一起使用?
【发布时间】:2018-04-08 03:13:48
【问题描述】:

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

我对@9​​87654325@ 感到困惑,因为 m 是一个对象,唯一将类和参数结合在一起的情况是构造函数,但显然不是。

我是 C++ 的初学者。但是,与 Ruby 不同的是,C++ 中没有什么技巧。

为了对C++有一个深入的发现,有没有大神可以给我一个原则性的解释?

【问题讨论】:

  • 不,m 不是一个类,它是一个变量。
  • 在 c++ 中,您可以定义自己的运算符,最流行的运算符之一是 operator[],但 operator() 也是可能的。检查这个:boost.org/doc/libs/1_57_0/boost/numeric/ublas/matrix.hpp 并搜索 const_reference operator () (size_type i, size_type j)
  • 另外,所有的左值都可以赋值。 |在向Stack Overflow 提问之前,您需要了解有关 C++ 的更多信息,否则此类问题将被视为不清楚。
  • @user202729,我的意思是对象,这是我的书面错误。
  • @Frederik.L,非常感谢。在我的想象中,() 不是运算符,因为函数调用和新对象。现在我对 C++ 有了新的理解。

标签: c++ matrix boost assign ublas


【解决方案1】:

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

如果你看一下Boost的matrix.hpp的源代码,其中定义了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 上)。

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2014-03-24
    相关资源
    最近更新 更多