6

我正在写一Matrix2D堂课。一开始我使用构造函数如下,

我的代码:

Matrix2D(float a,float b, float c,float d)
{
    a_=a;
    ....
} 

但是,我刚刚意识到如果我可以使用 multi Dimension 会好很多array [2][2]。这就是问题所在,如何为数组编写构造函数?

class Matrix
{
    float matrix[2][2];
    public:
    Matrix2D(float a,float b,float c, float d)
    {
        matrix[2][2]={a,b,c,d} // not valid
    }
}

只是为了让您知道,我不要求提供完整的代码。我只需要有人让我走上正轨。

4

5 回答 5

4

对于C++11,您可以执行以下操作:

Matrix(float a,float b,float c, float d) :
   matrix{{a,b},{c,d}}
{
}

C++03没有干净的替代品。

于 2012-10-01T19:21:25.447 回答
2
matrix[0][0] = a; // initialize one element

等等。

于 2012-10-01T19:11:02.813 回答
1

matrix[0][0] = 你想要的值矩阵 [n][n] = 你想要的值,但在循环中计数,因此矩阵的大小可以是动态的,或者您可以稍后重用您的代码。

for(int ii(0); ii < first dimension size; ++ii)
{
   for(int ll(0); ii < second dimension size; ++ll)
   {
     matrix[ii][ll] = value you want;
   }
}

这将使您的代码在此应用程序之外更具可扩展性和更有用,也许它没有用,或者它可能是。

于 2012-10-01T19:29:07.757 回答
0

如果它将是一个 2X2 矩阵,那么您可以传递一个浮点数组,然后循环遍历它。

例如

for(int x = 0;x<4;x++)
{
    matrix[0][x] = myarray[x];
}
于 2012-10-01T19:15:18.123 回答
0

如果您有 C++11 编译器,则 Luchian 的版本是最好的。这是适用于所有 C++ 版本的一个:

struct matrix_holder { float matrix[2][2]; };

class Matrix : matrix_holder
{
    static matrix_holder pack(float a,float b,float c, float d)
    {
        matrix_holder h = { {{a, b}, {c, d}} };
        return h;
    }

public:
    Matrix(float a,float b,float c, float d) : matrix_holder(pack(a,b,c,d))
    {
    }
};

优化器将内联帮助器。

于 2012-10-01T19:27:39.063 回答