【问题标题】:Pass a bidimensional array and store as a class menber传递一个二维数组并作为类成员存储
【发布时间】:2020-09-22 20:58:56
【问题描述】:

我有一个带有二维整数数组的 C++ 类。

该成员由该类的一种方法设置。

class MyClass {
  private:
    int values[][4];

  public:
    MyClass();
    void setValues(int values[][4]);

如果我这样做:

MyClass::setValues(int values[][4]) {
  Serial.println(values[0][0]);
}

一切正常,没有错误。但如果我这样做:

MyClass::setValues(int values[][4]) {
  this->values = values;
}

我收到invalid use of array with unspecified bounds 错误。

我需要这个二维空间来使用这个类的其他方法。

如何将其保存为班级成员?

【问题讨论】:

  • std::vector<int> 作为计算的二维向量,或 std::vector<std::vector<int>> 作为向量的向量的整数。
  • 这是一个大小不一的数组,所以你不能像这样把它放在class 中。它需要一个固定的大小。如果可用,请使用std::vector,如果没有,请使用new[]
  • 忘记 C 风格的数组存在。专门使用std::arraystd::vector 代替它们。过上更幸福的生活。
  • std::vector<:vector>> 不起作用...我需要添加一些库吗?

标签: c++ class arduino


【解决方案1】:

我用 ArduinoIDE libiries 中的 Vector.h 解决了这个问题。

但是,我不使用 Vector of Vectors...

首先,我创建了一个struct

struct MyStruct {
  int a;
  int b;
  int c;
  unsigned long d;
  
  MyStruct(int a, int b, int c, unsigned long d) {
    this->a = a;
    this->b = b;
    this->c = c;
    this->d = d;
  }
};

然后,将我的方法更改为void set(Vector&lt;MyStruct&gt; steps); 并这样调用:

  MyStruct steps[6] = {MyStruct(50, 0, 0, 100),
                      MyStruct(20, 0, 0, 100),
                      MyStruct(50, 0, 0, 100),
                      MyStruct(20, 0, 0, 100),
                      MyStruct(50, 0, 0, 100),
                      MyStruct(0, 0, 0, 500)
                     };
  Vector<MyStruct> vector(steps, 6);
  myClass.setSteps(vector);

它现在可以工作了:D

【讨论】:

  • Arduino 不是一个完整的 C++ 编译器。一些响应者没有意识到这一点,并建议像 std::vector 这样在常规 C++ 中工作但在 Arduino 中不工作的解决方案。
猜你喜欢
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
相关资源
最近更新 更多