将2D数组传递给函数/构造函数

时间:2020-08-08 16:31:34

标签: c++ pointers multidimensional-array arguments

无法将float [3] [3]转换为float **

我正在编写一个与矩阵有关的程序,作为一种学习实践

但是我遇到错误,无法将float matrix[3][3]分配给float** 我知道2D array是指针的指针,所以float **

我对该项目的目标是编写一个简单的Matrix类来创建矩阵并执行一些基本的矩阵运算,例如加法和乘法。

我遇到以下错误:

In file included from main.cpp:2:0:
./matrix.h:12:5: note: candidate: Matrix::Matrix(int, int, float**)
     Matrix(int, int, float **elements);
     ^~~~~~
./matrix.h:12:5: note:   no known conversion for argument 3 from 
‘float [3][3]’ to ‘float**’

我知道从float[3][3]更改参数类型将解决该问题。但是矩阵的大小不是固定的,这就是为什么我选择float**

这是我的代码的一部分:

main.cpp

#include"Matrix.h"

int main()
{
    float Identity[3][3] = 
    {
        {1.0, 0.0, 0.0},
        {0.0, 1.0, 0.0},
        {0.0, 0.0, 1.0}    
    };
    
    Matrix identity = Matrix(3, 3, Identity);
}

Matrix.h

class Matrix
{
private
    MatrixData _matrix = MatrixData();
    
    Matrix(int rows, int columns, float **elements)
    {
        _matrix.rows = rows;
        _matrix.columns = columns;
        
        _matrix.elements = new float[rows * columns];
        
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < columns; j++)
                _matrix.elements[(i * columns) + j] = elements[i][j];

    }    
}

MatrixData.h

struct MatrixData
{
    unsigned char rows;
    unsigned char columns;
    float *elements;
};

MatrixData class中,元素存储为连续数组。

要创建新的矩阵,必须将2D array传递到类constructor中。

如果构造函数arg类型为float * 然后我在构造函数中传递Identity[0],就可以了。

我想要的是传递Identity而不是Identity[0]&Identity[0][0]之类的东西。

任何人都可以告诉我解决方案吗

谢谢。

1 个答案:

答案 0 :(得分:2)

2D数组是连续存储的,因此您可能应该执行以下示例:

#include <iostream>

template<size_t N1, size_t N2>
void output(const float (&elements)[N1][N2])
{
    for (size_t i = 0; i < N1; i++)
    {
        for (size_t j = 0; j < N2; j++)
            std::cout << elements[i][j] << ' ';
        std::cout << std::endl;
    }
}
int main()
{

    float elements[3][3] = {
    {1,2,3},
    {1,2,3},
    {1,2,3}
    };
    output<3, 3>(elements);
}

请注意我是如何使用模板的,因为数组大小是静态的,这是您犯的另一个错误

编辑:我了解您要执行的操作,方法如下:

使Matrix类成为使用模板参数行和列的模板类,并将elements参数更改为float elements[rows][columns]

template<size_t rows, size_t columns>
class Matrix
{
private:
    MatrixData _matrix = MatrixData();
public:
    Matrix(float elements[rows][columns])
    {
        _matrix.rows = rows;
        _matrix.columns = columns;

        _matrix.elements = new float[rows * columns];

        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++)
                _matrix.elements[(i * columns) + j] = elements[i][j];

    }
};

然后,您必须删除行和列构造函数参数,因为您已经将它们作为模板参数。

现在对象声明应如下所示:

int main()
{
    float Identity[3][3] =
    {
        {1.0, 0.0, 0.0},
        {0.0, 1.0, 0.0},
        {0.0, 0.0, 1.0}
    };

    Matrix<3, 3> identity(Identity);
}
相关问题