我正在为Arduino开发LED推子。为此,我编写了一个定义所有内容的类。但是从昨天开始,我遇到了一个问题,我无法解决。
到目前为止,这是我的代码:

class LED {
    int pins[4];
    int r = 0;
    int g = 0;
    int b = 0;
    int task = 1;
    int taskgoal = 255;
  public:
    void newTask() {
      ...
    }
    void newGoal() {
      ...
    }
    boolean taskFinished() {
      ...
    }
    void runTask() {
      if (taskFinished()) {
        newTask();
        newGoal();
        cout << "New Task and new Goal.\n";
      }
      int current;
      switch (task) {
        ...
      }
      if (current < taskgoal) {
        switch (task) {
          case 1:
            cout << r << "+1" << "\n";
            this->redefine(this->r + 1, this->g, this->b);
            cout << r << "+1" << "\n";
            break;
          case 2:
            cout << g << "+1" << "\n";
            this->redefine(this->g, this->g + 1, this->b);
            break;
          case 3:
            cout << b << "+1" << "\n";
            this->redefine(this->r, this->g, this->b + 1);
            break;
        }
      } else if (current > taskgoal) {
        ...
      }
      analogWrite(pins[0], this->r);
      analogWrite(pins[1], this->g);
      analogWrite(pins[2], this->b);
      return;
    }
    void ledinit(int p[]) {
      this->r = random(1, 255);
      this->g = random(1, 255);
      this->b = random(1, 255);
      for (int i = 1; i < 3; i++) {
        pins[i] = p[i];
        pinMode(pins[i], OUTPUT);
      }
      pins[3] = p[3];
      analogWrite(pins[0], this->r);
      analogWrite(pins[1], this->g);
      analogWrite(pins[2], this->b);
      analogWrite(pins[3], LOW);
      newTask();
      newGoal();
      runTask();
      return;
    }
    void redefine(int rr, int gg, int bb) {
      r = rr;
      g = gg;
      b = bb;
      return;
    }
};
std::vector< LED >leds;

void setup() {
  Serial.begin(9600);
  LED l1;
  int l1pins[4] = {11, 9, 8, 10};
  l1.ledinit(l1pins);
  leds.push_back(l1);
}

void loop() {
  for (LED l : leds) {
    l.runTask();
    cout << "Run Task" << "\n";
  }
  delay(100);
}


(垃圾箱:http://pastebin.com/pQMEkG1a
在第76行中,我尝试使用函数redefine将r值加1。我也直接用this->r++;this->r += 1;尝试了一下,但是结果都一样。它将1加到r变量中。但是在下一个循环中,它还是和开始时一样的值。输出结果如下所示:

Run Task
45+1
46+1
Run Task
45+1
46+1
Run Task
45+1
46+1


但是为什么每次都为45?我认为这对我来说很容易犯错,但我找不到。

最佳答案

查看代码,我希望您的问题出在for (LED l : leds)

这个基于范围的for循环遍历LED,从每个元素获取一个副本,您将在该副本上运行任务。

我建议编写以下内容:for (LED &l : leds)以防止复制。

看起来您的编译器支持C ++ 11,所以您将来可能希望通过将以下成员函数添加到类LED中来防止类似问题:LED(const LED &) = delete;the rule of five中的其他一些成员函数。这样可以防止从led复制任何内容。可能需要一些移动构造函数才能在向量中添加LED。

关于c++ - 类(class)变量自行重置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38930792/

10-14 16:13