我正在构建我自己的矩阵类来巩固我对C++的理解。它是模板化的,所以我可以有一个int矩阵或一个浮点数或布尔矩阵。我不打算实现一个拷贝构造函数或赋值操作符或析构函数,因为我不会有任何动态成员元素,但如果我有:模板类中的C++赋值运算符实现
Matrix<float,3,4> mat1;
Matrix<int,45,45> mat2;
mat1 = mat2;
它返回以下错误:
/Users/Jake/Dropbox/C++/test.cpp: In function ‘bool test1()’:
/Users/Jake/Dropbox/C++/test.cpp:23: error: no match for ‘operator=’ in ‘m2 = m1’
/Users/Jake/Dropbox/C++/Matrix.h:22: note: candidates are: Matrix<float, 3u, 4u>& Matrix<float, 3u, 4u>::operator=(const Matrix<float, 3u, 4u>&)
其中,如果两个矩阵都是float或者都是int,那没关系。尺寸不必匹配。所以默认的赋值运算符工作得很好,除非它们是不同的类型。所以,我实现我自己的赋值操作符:
template <class T, unsigned int rows, unsigned int cols>
template <class T2, unsigned int rows2, unsigned int cols2>
Matrix<T, rows2, cols2> & Matrix<T,rows,cols>::operator= (const Matrix<T2, rows2, cols2> & second_matrix){
unsigned int i,j;
for (i=0; i < rows2; i++){
for (j=0; j < cols2; j++){
data[i][j] = second_matrix(i,j);
}
}
this->_rows = rows2;
this->_cols = cols2;
return *this;
}
这工作,如果他们是不同类型的,但相同的尺寸─但在第二个值从第二类型转换为第一。我的问题是,我如何设置它以便它们可以是不同的类型和不同的尺寸,并且将其设置为指向第二个或第二个副本?
2010-12-09 23:10:31
它已经被解释为你不能,C++阻止你在矩阵理论中不存在的矩阵上执行操作 - 你不能指定矩阵,哪些维度不相同。 –