假设我们想从给定矩阵中减去一些值。 怎么可能/我应该重载该运算符。
的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;
}
}
答案 0 :(得分:1)
您的代码正在尝试从Matrix
中减去double
,但您的问题要求从double
中减去Matrix
。这是两个不同的操作。你真的想做什么?
在后一种情况下,您需要重载减法运算符,而不是转换运算符,例如:
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;