使用C ++

时间:2019-06-14 20:03:09

标签: c++

我在一行中用数组初始化对象时遇到麻烦,有人可以帮我弄清楚语法吗?

该课程如下:

struct Matrix4
{
   float mElements[16];
   Matrix4(float mElements[])
   {
       memset(&this->mElements, 0, sizeof(this->mElements));
       for (int i = 0; i < 16; i++)
            this->mElements[i] = mElements[i];
   }
}

我正在尝试通过以下方式对其进行初始化:

Matrix4 mMatrix = Matrix4({1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1});

我得到的错误是:

no instance of constructor "Matrix4::Matrix4" matches the argument list 

谢谢

1 个答案:

答案 0 :(得分:5)

如果您想继续使用原始数组,可以改用const引用数组:

struct Matrix4
{
   float mElements[16];
   Matrix4(const float (&mElements)[16])
   {
       for (int i = 0; i < 16; i++)
            this->mElements[i] = mElements[i];
   }
};

Matrix4 mMatrix = Matrix4({1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1});

但是您应该考虑改用std::array,它具有更直观的语义:

#include <array>

struct Matrix4
{
   std::array<float, 16> mElements;
   Matrix4(const std::array<float, 16> & mElements) :
      mElements(mElements) {}
};

Matrix4 mMatrix = Matrix4({1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1});

请注意,您具有聚合类型,因此无需提供构造函数:

#include <array>

struct Matrix4
{
   std::array<float, 16> mElements;
};

Matrix4 mMatrix = {1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1};