2010-12-09 96 views
1

我正在构建我自己的矩阵类来巩固我对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; 
} 

这工作,如果他们是不同类型的,但相同的尺寸─但在第二个值从第二类型转换为第一。我的问题是,我如何设置它以便它们可以是不同的类型和不同的尺寸,并且将其设置为指向第二个或第二个副本?

+0

我该如何设置它以便它们可以是不同的类型和不同的尺寸,并将其设置为指向第二个或第二个副本? 它已经被解释为你不能,C++阻止你在矩阵理论中不存在的矩阵上执行操作 - 你不能指定矩阵,哪些维度不相同。 – 2010-12-09 23:10:31

回答

1

你遇到的问题是你有三种类型,但你只提到两种。从根本上说,

Matrix<float,3,4> mat1; 
Matrix<int,45,45> mat2; 
mat1 = mat2; 

不能工作,因为分配的结果应该是Matrix<float, 45, 45>,但mat1Matrix<float, 3, 4>类型。这不可能改变。

是否有原因矩阵的尺寸必须是类型的一部分?似乎你真的想要动态地改变这个东西。只需要:'

template <class T> 
class Matrix 
{ 
    unsigned int rows; 
    unsigned int cols; 
    public: 
    Matrix(numrows, numcols): rows(numrows), cols(numcols) {} 
}; 

etc ...然后你可以在运行时改变矩阵的大小。

1

how can I set it up so that they can be different types and different dimensions, and just set this to point at the second, or a copy of the second?

你不知道。

mat不指向Matrix<float,3,4>;它是一个Matrix<float,3,4>。它永远不可能是别的。没有办法将mat变成Matrix<int,45,45>

如果你想能够指向不同的对象,你需要使用指针(或引用)。为了能有一个指针可以指向的Matrix的任何专业,你需要创建一个基类,从基类派生Matrix

class MatrixBase { }; 

template <typename T, unsigned Rows, unsigned Columns> 
class Matrix : public MatrixBase { }; 

然后,您可以使用MatrixBase*以点任何Matrix类型的对象,您可以使用MatrixBase&来引用任何Matrix类型的对象。您需要将尽可能多的共享功能放入MatrixBase课程或使用虚拟功能。

+0

你确定要'行'和'列'为'typename`而不是`unsigned int`吗? – SingleNegationElimination 2010-12-09 23:04:19

+0

@TokenMacGuy:你是什么意思?他们是'未签名'! :-O(谢谢,哈哈) – 2010-12-09 23:05:16