【问题标题】:c++ class constructor for array用于数组的c ++类构造函数
【发布时间】:2012-09-22 16:00:44
【问题描述】:

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

我的代码:

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

但是,我刚刚意识到如果我可以使用多维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
    }
}

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

【问题讨论】:

  • 顺便说一句,类名和构造函数名需要匹配。
  • 谢谢,只是错字,它们在源代码中匹配

标签: c++ arrays class


【解决方案1】:
matrix[0][0] = a; // initialize one element

等等。

【讨论】:

  • 谢谢你的答案。我就是这样做的
【解决方案2】:

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

例如

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

【讨论】:

  • @LuchianGrigore 怎么无效?
  • @coolbartek 如果matrix 被声明为float matrix[2][2] 那么matrix[0][3] 显然是无效的。
  • 对我来说看起来不错,二维数组实际上是一个普通数组,您可以通过[0][x]访问其中的元素。数组[x][y] 与数组[0][x*y] 相同
  • @coolbartek:你不是说array[y][x]array[0][x+y*width]一样吗?
  • @Luchian,您是否忘记了 a[i]*(a + i) 的内置类型相同?
【解决方案3】:

对于 C++11,您可以这样做:

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

C++03 没有干净的替代方案。

【讨论】:

  • 你需要去掉括号,即matrix{{a,b},{c,d}},因为它是一个数组。
  • LWS 使用 gcc 4.7.2
  • 好的,我已经尝试过了,显然 vs 2010 不支持此功能,所以我将不得不使用“matrix[0][0]=a;”等等。谢谢支持
【解决方案4】:

如果你有一个 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))
    {
    }
};

优化器将内联帮助器。

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多