【发布时间】:2018-07-03 00:59:56
【问题描述】:
我编写了一些代码,设法混合了类模板、类继承和运算符重载,但我不知道如何解决有关运算符使用的问题。我有一个包含大量代码的基类(特别是运算符重载实现和数据持有者):
template <typename _type>
class baseMatrix {
public:
baseMatrix();
~baseMatrix();
//operators
baseMatrix<_type>& operator= (baseMatrix<_type> _mat);
template <typename _input_type> baseMatrix<_type>& operator*= (_input_type _val);
template <typename _input_type> baseMatrix<_type>& operator/= (_input_type _val);
template <typename _input_type> baseMatrix<_type>& operator+= (_input_type _val);
template <typename _input_type> baseMatrix<_type>& operator-= (_input_type _val);
template <typename _input_type> baseMatrix<_type>& operator*= (const baseMatrix<_input_type>& _mat);
template <typename _input_type> baseMatrix<_type>& operator/= (const baseMatrix<_input_type>& _mat);
template <typename _input_type> baseMatrix<_type>& operator+= (const baseMatrix<_input_type>& _mat);
template <typename _input_type> baseMatrix<_type>& operator-= (const baseMatrix<_input_type>& _mat);
protected:
std::vector<_type> data;
};
/* ... */
template <typename _type>
template <typename _input_type>
baseMatrix<_type>& baseMatrix<_type>::operator*=(_input_type _val) {
for (int i = 0; i < data.size(); ++i) data[i]*=_val;
return *this;
};
template <typename _type>
template <typename _input_type>
baseMatrix<_type>& baseMatrix<_type>::operator*=(const baseMatrix<_input_type>& _mat) {
for (int i = 0; i < data.size(); ++i) data[i]*=_mat.data[i];
return *this;
};
/* remaining operator overload functions */
我为标量和类参数重载了运算符。然后我有一个额外的类matrix2D 从baseMatrix 继承这些运算符:
template <typename _type>
class matrix2D : public baseMatrix<_type> {
public:
matrix2D(int _rows, int _cols);
matrix2D(int _rows, int _cols, _type _val);
~matrix2D();
_type& operator()(int _r, int _c);
_type& at(int _r, int _c);
protected:
int nRows,nCols;
using baseMatrix<_type>::data;
};
但是,在实例化这些类时,我只能调用标量运算符,例如使用*= 带有两个 matrix2D 对象会导致编译错误:
In file included from test.cpp:1:
baseMatrix.hpp: In instantiation of ‘baseMatrix<_type>& baseMatrix<_type>::operator*=(_input_type) [with _input_type = matrix2D<float>; _type = float]’:
test.cpp:29:6: required from here
baseMatrix.hpp:56:47: error: no match for ‘operator*=’ (operand types are ‘__gnu_cxx::__alloc_traits<std::allocator<float>, float>::value_type’ {aka ‘float’} and ‘matrix2D<float>’)
for (int i = 0; i < data.size(); ++i) data[i]*=_val;
另一方面,如果我实例化一个 baseMatrix 对象,它可以编译(由于其他原因在运行时失败,即未初始化数据):
int main(int argc, char const *argv[]){
matrix2D<float> M1(5,5,0.0);
matrix2D<float> M2(3,3,6.0);
baseMatrix<float> testM;
M2*=0.47; // works
M2*=M1; // does not compile
M2*=testM // runtime error (segfault)
}
显然,运算符重载不适用于派生类,正确的语法是什么?
编辑:我意识到问题在于多个运算符重载。出于某种原因,如果我只声明运算符以 baseMatrix 对象作为参数,则它能够编译,反之亦然。
【问题讨论】:
-
离题,但你真的不应该用下划线开始标识符。
-
提示 - 您定义了如何将矩阵乘以浮点数,而不是浮点数乘以矩阵,您的代码正在这样做。
-
@PaulMcKenzie 你这是什么意思?
-
您的代码正在执行以下操作:
data[i] *= _val。简而言之float *= matrix。哪一个重载与该调用匹配?
标签: c++ templates inheritance operator-overloading