模板矩阵类中操作符*的多重重载
Multi-overloading of operator* in template matrix class
我有一个模板类myMatrix
主要像:
template<class T, int row, int col>
class myMatrix{
T *_mat;
public:
template<int r, int c> using matrix_t = T[r][c];
myMatrix(const matrix_t<row, col> &);
myMatrix(const myMatrix<T, row, col> &);
myMatrix &operator=( const myMatrix<T, row, col>& );
//...
// next is the part of * overloading
myMatrix<T, row, col> operator*(const T& scalar);
typename< int c2 >
myMatrix<T, row, c2> operator*( const myMatrix<T, col, c2>& );
typename< int c2 >
myMatrix<T, row, c2> operator*( const matrix_t<col, c2>& );
typename< int r2 >
friend myMatrix<T, r2, col> operator*( const matrix_t<r2, row>&, const myMatrix<T, row, col>& );
// ...
};
然后设计另一个类Reference
:
template<int dim, int loop>
class Reference{
myMatrix<int, dim, loop> _matA;
myMatrix<int, dim, 1> _matC;
public:
Reference(const myMatrix<int, dim, loop> &, const Matrix<int, dim, 1> &);
Reference(const Reference<dim, loop> &);
Reference<dim, loop> &operator=(const Reference<dim, loop> &);
// ...
friend Reference<1, loop> operator*(const Matrix<int, 1, dim> &alpha,
const Reference<dim, loop> & ref)
{
return Reference(alpha * ref._matA, alpha * ref._matC); // **Problem!!!**
}
// ...
};
当我用
这样的东西测试代码时 const int matA[3][3] = {1,2,3,4,5,6,7};
const int matC[3][1] = {1,2,3};
const int alp[][3] = {1,2,2};
Reference<3,3> ref(matA, matC);
Matrix<int, 1, 3> alpha(alp);
// Reference<1,3> ref_t = alp * ref;
Reference<1,3> ref_t = alpha * ref; // **can not compile!!!**
出现问题:
二进制'*':没有找到左操作数类型为'const myMatrix'的操作符(或者没有可接受的转换)…
我的问题来了:
在
myMatrix
类的所有+4重载中,是否存在冗余?也许只是
typename< int c2 > myMatrix<T, row, c2> operator*( const myMatrix<T, col, c2>& );
的重载版本可以服务于以下两个重载,因为built-in 2d-array like arr[][]
可以转换为myMatrix
由于我的构造函数myMatrix(const matrix_t<row, col> &);
?编译错误的原因是什么?
编译器错误提示你做错了什么:
你有二进制'*':没有找到左操作数类型为'const myMatrix'的操作符
operator*(const myMatrix&);
但没有
operator*(const myMatrix&) const;
所以alpha * ref
不能匹配(因为alpha
是const&
)。
通常实现T::operator*
的方法是
T& operator*=(const T&);
T operator*(const T&) const;
或者(更好的),使*
操作符成为带有两个参数的自由函数(如果可能需要提升左参数,这种方法会更好)。
相关文章:
- 重载操作符+:表达式必须是整型或无作用域枚举类型
- 重载操作符
- 如何重载操作符==外模板类使用友元函数
- 重载*操作符,使其在左右两边都工作
- 重载操作符<对于非随机迭代器
- 在c++中重载操作符的时间和原因
- 如何在c++中重载=操作符来通过引用进行复制
- 如何在c++中获取定义为友元的重载操作符的地址
- 使用重载操作符的文件操作表达式没有给出预期的结果
- 重载操作符()
- 重载操作符()并在类内使用
- 类中的重载操作符+
- 定时使用重载操作符
- c++带类的重载操作符
- 用列表容器重载[]操作符
- 重载操作符=
- 任何重载操作符()的静态检测
- 重载操作符以处理类对象
- 在使用另一个类的类中重载操作符==
- 派生类和基类中的重载操作符不同