使用带有2d参数的构造函数的c ++错误c2440

时间:2014-10-29 14:14:08

标签: c++ arrays constructor compiler-errors

我有一个矩阵类,其中2d元素数组作为成员变量。并且有一个带有2d数组的自定义ctor作为参数。奇怪的是,当我尝试测试它时,它会抛出错误C2440:错误C2440:'' :无法转换为' float [3] [3]'到' Matrix'。这是代码:

Matrix.h

class Matrix
{
    public:
        Matrix();
        ~Matrix();
        Matrix(const Matrix& other);
        Matrix( float e_11, float e_12, float e_13,
                  float e_21, float e_22, float e_23, \
                  float e_31, float e_32, float e_33);

        Matrix(float *elements[]);

    private:

        float* m_ElementsA; //< The array of elements of the vector 
}

Matrix.cpp

#include "../include/Matrix.h"

Matrix::Matrix()
{
    m_ElementsA = new float[9];
    for (int i = 0; i < 9; ++i)
    {
        *(m_ElementsA + i) = 0.0f;
    }
}

Matrix::~Matrix()
{
    delete[] m_ElementsA;
}

Matrix::Matrix(const Matrix& other)
{
    m_ElementsA = new float[9];
    unsigned int row, column;

    for (int i = 0; i < 9; ++i)
    {
        GetRowColumnFromIndex(i, row, column);
        *(m_ElementsA + i) = other.GetElement(row, column);
    }
}

Matrix::Matrix( float e_11, float e_12, float e_13, \
                float e_21, float e_22, float e_23, \
                float e_31, float e_32, float e_33)
{
    m_ElementsA = new float[9];

    *m_ElementsA = e_11;
    *(m_ElementsA + 1) = e_12;
    *(m_ElementsA + 2) = e_13;
    *(m_ElementsA + 3) = e_21;
    *(m_ElementsA + 4) = e_22;
    *(m_ElementsA + 5) = e_23;
    *(m_ElementsA + 6) = e_31;
    *(m_ElementsA + 7) = e_32;
    *(m_ElementsA + 8) = e_33;
}

Matrix::Matrix( float *elements[])
{
    m_ElementsA = new float[9];
    unsigned int row, column;

    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            *(m_ElementsA + (i * 3) + j) = elements[i][j];
        }
    }
}

的main.cpp

int _tmain(int argc, _TCHAR* argv[])
{   
    float arr[3][3] =
    {
        {1.1f, 2.2f, 3.3f},
        {4.4f, 5.5f, 6.6f},
        {7.7f, 8.8f, 9.9f}
    };

    Matrix mat3 = Matrix(arr);

    return(0);
}

我在这里做错了什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您从float[3][3]数组转换为float **(您的构造函数)的转换无效:

Matrix::Matrix(float *elements[])

因为你正在处理固定的3x3矩阵,所以你应该做类似的事情:

Matrix::Matrix(float(&elements)[3][3]) // Reference to 3x3 array