简体   繁体   English

在C ++中存储对数组的引用

[英]Storing a reference to an array in C++

I have an array: 我有一个数组:

const int neoPixelCount = 40;
CRGB neoPixels[neoPixelCount];

And I have a Dancer , that needs to hold onto a reference of that array. 我有一个Dancer ,需要保留该数组的引用。 It has an init method that looks like this: 它具有一个如下所示的init方法:

// .h
class Dancer {
  public:
    CRGB neoPixels[];
    void init(CRGB neoPixels[]);
}

// .cpp
void Dancer::init(CRGB _neoPixels[]) {
  neoPixels = _neoPixels;
}

But when I call this, the compiler won't let me pass the reference to array. 但是当我调用它时,编译器不会让我将引用传递给数组。

dancer->init(neoPixels);

Which yields: 产生:

discobot/Dancer.cpp: In member function 'void Dancer::init(CRGB*)': discobot / Dancer.cpp:在成员函数'void Dancer :: init(CRGB *)'中:

discobot/Dancer.cpp:14: error: incompatible types in assignment of 'CRGB*' to 'CRGB [0]' discobot / Dancer.cpp:14:错误:“ CRGB *”到“ CRGB [0]”的分配中的类型不兼容

What's the right syntax magic to make this work, and why? 使这项工作正确的语法魔术是什么,为什么?

You just need to change CRGB neoPixels[]; 您只需要更改CRGB neoPixels[]; to CRGB* neoPixels; CRGB* neoPixels; in the class member declaration, because you want to store a pointer (to the array) rather than a zero/unknown-length array. 在类成员声明中,因为您要存储一个指向数组的指针,而不是零/未知长度的数组。

If you want a reference to an array as a class member your should have something like that 如果您希望将数组作为类成员进行引用,则应具有类似的内容

class Dancer 
{
public:
    int (&neoPixels)[40]; // reference to an array of 40 elements
    Dancer(int (&neoPixels)[40]) : neoPixels(neoPixels) { }
};

The member neoPixels is a reference to an array of 40 elements (pardon the change to int , it was to do the checks in my machine). 成员neoPixels是对40个元素的数组的引用(请更改为int ,这是在我的机器上进行检查)。

Now since that's a reference it should be initialized in the constructor's initializer list. 现在,由于这是一个引用,因此应在构造函数的初始化程序列表中对其进行初始化。

To generalize the above idea, your class could be a template holding references to arrays of compile time known sizes. 为了概括上述思想,您的类可以是一个模板,其中包含对编译时已知大小的数组的引用。

template<size_t N>
class Dancer
{
    public:
    int (&neoPixels)[N]; // reference to an array of N elements
    Dancer(int (&neoPixels)[N]) : neoPixels(neoPixels) { }
};

I would suggest changing Dancer to: 我建议将Dancer更改为:

class Dancer {
  public:
    CRGB* neoPixels;
    void init(CRGB neoPixels[]);
}

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

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