【问题标题】:C++ operator overloading <double> - <Matrix> [duplicate]C++ 运算符重载 <double> - <Matrix> [重复]
【发布时间】:2017-12-07 17:40:54
【问题描述】:

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

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

【问题讨论】:

  • operator double 是一个转换运算符,应该返回 double 而不是 Matrix
  • 运算符 double 将 Matrix 转换为 double,而不是 double 转换为 Matrix。你的意思是有一个接受双精度的矩阵构造函数吗?
  • 你不能!但是,您可以重载operator-(double, Matrix);

标签: c++ templates matrix overloading operator-keyword


【解决方案1】:

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

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

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;

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 2020-11-08
    • 2011-10-27
    • 2012-12-22
    • 2016-09-26
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多