1

来自Boost 官方网站的示例代码:

#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++有深入的发现,有没有大神可以给我一个原则性的解释?

4

1 回答 1

2

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

如果您查看Boost的matrix.hppmatrix的源代码,其中定义了对象,确实有一个 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_)];
    }

/** 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 ()定义中的存在。

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

于 2018-04-08T05:43:00.907 回答