【发布时间】: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