基本上,我正在编写一个矩阵类,但我想用int[N][M]
变量初始化它。
我有这个工作(3,3矩阵(:
矩阵。h:
class Matrix {
private:
unsigned cols, rows;
int* data;
public:
Matrix(unsigned cols, unsigned row);
Matrix(int mat[3][3]);
}
matrix.cpp:
inline
Matrix::Matrix(unsigned cols, unsigned rows) : cols (cols), rows (rows) {
if (rows == 0 || cols == 0) {
throw std::out_of_range("Matrix constructor has 0 size");
}
data = new int[rows * cols];
}
Matrix::Matrix(int mat[3][3]) : Matrix(3, 3) {
for(unsigned row = 0; row < rows; row++) {
for(unsigned col = 0; col < cols; col++) {
(*this)(col, row) = mat[col][row];
}
}
}
然后我尝试实现一个模板构造函数:
template<int N, int M>
Matrix(int[N][M]) : Matrix(N, M) {
for(unsigned row = 0; row < rows; row++) {
for(unsigned col = 0; col < cols; col++) {
(*this)(col, row) = mat[col][row];
}
}
}
它似乎是编译的,但当我执行一个测试函数时:
void test() {
int tab[3][3] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
Matrix mat(tab);
}
我得到这个错误:
matrix.cpp:10:19: error: no matching function for call to ‘Matrix::Matrix(int [3][3])’
Matrix mat(tab);
尽管我是这样模板化的(在Matrix类下的.h文件中(:
template<> Matrix::Matrix<3, 3>(int[3][3]);
我真的需要一些帮助,以及如何用从0到10 的每一个int组合来初始化它
有几件事。。。
首先要注意,Matrix(int[N][M])
是不完整的,并且缺少一个参数名称。还要注意,它相当于Matrix(int(*)[M])
。
其次,数组维度的类型是size_t
,而不是int
。
第三,要传递实际的数组而不是指针,需要通过引用获取数组。
把所有这些放在一起,你的构造函数可能看起来像
template<size_t N, size_t M>
Matrix(int const (&mat)[N][M]) : Matrix(N, M)
{
for (size_t n = 0; n < N; ++n)
{
for (size_t m = 0; m < m; ++m)
{
(*this)(n, m) = mat[n][m];
}
}
}