C++ 运算符重载 <double> - <Matrix>

C++ operator overloading <double> - <Matrix>

假设我们要从给定矩阵中减去一些值。 could/should 我如何重载该运算符。

main.cpp

Matrix<double> m(10, 5);

auto r = 1.0 - m; //error: return type specified for 'operator double'

matrix.hpp

template <typename T>
class Matrix {
public:
  Matrix operator double(T val) {
    Matrix tmp(rows, cols);

    for (unsigned int i = 0; i < rows; i++)
      for (unsigned int j = 0; j < cols; j++) {
        const unsigned int idx = VecToIdx({i, j});
        tmp[idx] = val - this[idx];
      }

    return tmp;
  }
}

您的代码试图从 double 中减去 Matrix,但您的问题要求从 Matrix 中减去 double。这是两种不同的操作。你到底想做什么?

后一种情况,需要重载减法运算符,而不是转换运算符,eg:

template <typename T>
class Matrix {
public:
    Matrix operator- (T val) {
        Matrix tmp(rows, cols);
        for (unsigned int i = 0; i < rows; i++)
            for (unsigned int j = 0; j < cols; j++) {
                const unsigned int idx = VecToIdx({i, j});
                tmp[idx] = (*this)[idx] - val;
            }
        return tmp;
    }
};

Matrix<double> m(10, 5);

auto r = m - 1.0;