简体   繁体   English

数组初始化,初始化器值太多

[英]Array initialization, too many initializer values

I am defining a member variable like this:我正在定义一个这样的成员变量:

float m_Colors[4];

In the constructor I want to initialize it like this:在构造函数中,我想像这样初始化它:

m_Color = {0.0f, 0.0f, 0.0f, 1.0f};

Even though I have done this a million times before on this particular occasion I get the error "too many initializer values".即使我在这个特殊场合之前已经这样做了一百万次,我也会收到错误“太多初始化值”。 How could on these two very simple lines of code possibly be something wrong?这两行非常简单的代码怎么可能有问题? Please englighten me.请启发我。

You cannot reinitialize the array again with the initializer syntax (it was already default initialized when the class was constructed).您不能使用初始化器语法再次重新初始化数组(在构造class时它已经默认初始化)。

You can use the use a ctor initializer list to initialize the array when the class is constructed.您可以在构造class时使用使用ctor initializer list来初始化array

struct S 
{
    S( ) 
      :  floats_{ 1.0f, 2.2f, 3.3f, 4.4f } 
    {  }

private:
    float floats_[ 4 ];
};

If you want use initializer for built in array, you must do when declare it.如果你想为内置数组使用初始化器,你必须在声明它的时候做。 Otherwise you can use like this in your constructor:否则,您可以在构造函数中像这样使用:

float tmp[] = { 0.0f, 0.0f, 0.0f, 1.0f };
memcpy_s(m_Colors, 4, tmp, 4);

You can use std::array<...> as datatype for your member.您可以使用 std::array<...> 作为您的成员的数据类型。 This way you can initialise it with curly-braces and also assign it this way if needed plus you get some additional modern C++ benefits.通过这种方式,您可以使用花括号对其进行初始化,并在需要时以这种方式分配它,另外您还可以获得一些额外的现代 C++ 好处。

#include <array>

class Object
{
public:
    Object() : m_Colors{0.0f, 0.0f, 0.0f, 1.0f}
    {
    }

private:
    std::array<float, 4> m_Colors;
};

If you need to reassign:如果您需要重新分配:

void reinit()
{
    m_Colors = {0.0f, 0.0f, 0.0f, 1.0f};
}

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

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