简体   繁体   English

用于数组的c ++类构造函数

[英]c++ class constructor for array

I am writing a Matrix2D class. 我正在写一个Matrix2D课程。 At the beginning I was using constructor as folows, 一开始我使用构造函数作为folows,

My code: 我的代码:

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

However, I have just realized that it would be a lot better if I could use multi dimensional array [2][2] . 但是,我刚刚意识到如果我可以使用多维array [2][2]会好得多。 That's where the problem lies, How do I write constructor for array ? 这就是问题所在,如何为数组编写构造函数?

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
    }
}

Just to let you know, I don't ask for a complete code. 只是为了让您知道,我不要求提供完整的代码。 I just need someone to put me on a right track. 我只需要有人让我走上正轨。

For C++11 you can do: 对于C ++ 11,您可以:

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

There's no clean alternative for C++03 . C ++ 03没有干净的选择。

matrix[0][0] = a; // initialize one element

等等。

matrix[0][0] = value you want to matrix [n][n] = value you want but count up in a loop so the matrix can be dynamic in size or you can reuse your code later. 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;
   }
}

this will make your code more extensible and more useful outside of this application and maybe it's not useful or maybe it is. 这将使您的代码在此应用程序之外更具可扩展性和更有用,并且它可能没有用,也可能不是。

If it will be a matrix 2X2, then you can pass a float array and then loop through it. 如果它是一个矩阵2X2,那么你可以传递一个浮点数组然后循环它。

for example 例如

for(int x = 0;x<4;x++)
{
    matrix[0][x] = myarray[x];
}

Luchian's version is best if you have a C++11 compiler. 如果你有一个C ++ 11编译器,Luchian的版本是最好的。 Here's one that works for all versions of C++: 这是适用于所有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))
    {
    }
};

The optimizer will inline away the helper. 优化器将内联帮助器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM