C ++将2D数组传递给构造函数(没有已知的转换错误)

时间:2014-12-09 16:09:14

标签: c++ arrays c++11 multidimensional-array

我正在编写一个处理矩阵的程序。该程序使您能够在调用构造函数时输入矩阵:

CMatrix A(3,3,{{1,2,3},{4,5,6},{7,8,9}});

但它确定将2d数组作为int **发送到构造函数时会出现问题。我该如何解决?如果可能的话,我宁愿避免使用模板。我也在寻找一种干净的方式。

以下代码面临错误:

error: no matching function for call to ‘CMatrix::CMatrix(int, int, <brace-enclosed initializer list>)’ CMatrix A(3,3,{{1,2,3},{4,5,6},{7,8,9}});

 note:   no known conversion for argument 3 from ‘<brace-enclosed initializer list>’ to ‘int**’

代码:

#include <iostream>
using namespace std;

class CMatrix
{
    int rows,columns;
    int **members;
public:
    CMatrix(int rows,int columns);
    CMatrix(int rows,int columns,int **clone);
};

CMatrix::CMatrix(int rows,int columns)
{
    this->rows=rows;
    this->columns=columns;
    members=new int*[rows];
    for(int i=0;i<columns;i++)
        members[i]=new int[columns];
}

CMatrix::CMatrix(int rows,int columns,int **clone)
{
    CMatrix(rows,columns);
    for(int i=0;i<rows;i++)
        for(int j=0;j<columns;j++)
            members[i][j]=clone[i][j];
}

int main()
{
    CMatrix A(3,3,{{1,2,3},{4,5,6},{7,8,9}});
    ...
    return 0;
}

主叫:

g++ -std=c++11 test.cpp

1 个答案:

答案 0 :(得分:1)

{ ... }形式的数组初始值设定项只能用于初始化数组。例如

int myArray[] = {1,2,3,4};

要将数组传递给构造函数,必须先构建它。通过手动构建每一行:

int row1[] = {1,2,3};
int row2[] = {4,5,6};
int row3[] = {7,8,9};
int * matrix[] = {row1, row2, row3};
CMatrix(3,3,matrix);

或者通过动态构建整个事物:

int rows = 3;
int cols = 3;
int ** matrix = new int*[rows]; // allocate array of int pointers
for( int i = 0; i < rows; i++)
{
    matrix[i] = new int*[cols]; // allocate each array of ints
}
for (int i = 0; i<(rows*cols); i++)
{
    matrix[i/cols][i%cols] = i; //or whatever you need to set it to
}

CMatrix(rows,cols,matrix); // make your call

for( int i = 0; i < rows; i++)
{
    delete[] matrix[i]; //delete each int array
}
delete[] matrix; //delete matrix

您可以立即删除矩阵,因为CMatrix会复制值,而不是数组。