C++运算符*重载

C++ operator* overloading

本文关键字:重载 运算符 C++      更新时间:2023-10-16

我有下面的Matrix类,到目前为止它似乎运行良好

template<typename T, std::size_t M, std::size_t N>
class Matrix
{
    public:
        Matrix(const std::initializer_list<std::initializer_list<T>> m)
        {
            // snip
        }
        T& operator()(const std::size_t i, const std::size_t j)
        {
            return m_data.at(i + j * N);
        }
        const T& operator()(const std::size_t i, const std::size_t j) const
        {
            return m_data.at(i + j * N);
        }
        Matrix<T,M,N> operator*(const T n)
        {
            // snip
        }
    private:
        std::array<T, M * N> m_data;
};

然而,如果标量在运算符的右侧,则重载运算符*只允许标量乘法。即使标量在运算符的左侧,我也希望允许此操作,所以我尝试将其添加到Matrix.hpp文件:

template<typename T, std::size_t M, std::size_t N>
Matrix<T,M,N> operator*(const T lhs, const Matrix<T,M,N> &rhs)
{
    return rhs * lhs;
}

但这给了我以下错误:

In file included from test.cpp:1:0:
Matrix.hpp: In instantiation of ‘Matrix<T, M, N> operator*(T, const Matrix<T, M, N>&) [with T = double; long unsigned int M = 3ul; long unsigned int N = 3ul]’:
test.cpp:21:13:   required from here
Matrix.hpp:137:13: error: passing ‘const Matrix<double, 3ul, 3ul>’ as ‘this’ argument of ‘Matrix<T, M, N> Matrix<T, M, N>::operator*(T) [with T = double; long unsigned int M = 3ul; long unsigned int N = 3ul]’ discards qualifiers [-fpermissive]
  return rhs * lhs;

如果我从矩阵rhs参数中删除const,代码就会编译并正常工作。我想了解为什么代码不使用const进行编译?

您需要使operator*成为免费函数。(你需要两个它们,一个标量在右边,一个在左边。)您可能还想要operator*=;使用这个可能很方便操作员来实现两个CCD_ 7。

当您将运算符编写为成员方法时,第一个参数始终是类的"this"实例。如果要编写scalar * matrix,则必须将运算符编写为非成员函数。这通常是作为朋友的方法。

template<typename T>
Matrix<T> operator*(T const& n, Matrix<T> m)
{
    // snip
}
template<typename T>
Matrix<T> operator*(Matrix<T> m, T const& n)
{
    return n * m;
}