当我尝试编译Arduino草图时,我收到此错误。我没有看到它认为我试图在没有参数的情况下调用Counter::Counter
。这是怎么回事?
sketch/periodic_effect.cpp: In constructor 'PeriodicEffect::PeriodicEffect(uint32_t, uint32_t, Counter::Mode)':
periodic_effect.cpp:4: error: no matching function for call to 'Counter::Counter()'
PeriodicEffect::PeriodicEffect( uint32_t durationMs, uint32_t periods, Counter::Mode mode) : Runnable(), periods(periods) {
periodic_effect.cpp
#include <Arduino.h>
#include "periodic_effect.h"
PeriodicEffect::PeriodicEffect( uint32_t durationMs, uint32_t periods, Counter::Mode mode) : Runnable(), periods(periods) {
intervalMs = durationMs / periods;
index = Counter(intervalMs, mode);
}
void PeriodicEffect::run() {
uint32_t currTimeMs = millis();
if( (currTimeMs - prevTimeMs) > intervalMs ) {
applyChange();
prevTimeMs = currTimeMs;
index.increment();
}
}
periodic_effect.h
#ifndef PERIODIC_EFFECT_H
#define PERIODIC_EFFECT_H
#include "counter.h"
#include "runnable.h"
class PeriodicEffect : public Runnable {
public:
PeriodicEffect( uint32_t durationMs, uint32_t periods, Counter::Mode mode = Counter::Mode::RESETTING );
Counter index;
private:
uint32_t intervalMs, periods, prevTimeMs;
virtual void applyChange() = 0;
void run();
virtual void setup() = 0;
};
#endif
counter.h
#ifndef COUNTER_H
#define COUNTER_H
#include <stdint.h>
class Counter {
public:
enum Mode { RESETTING, RETURNING };
Counter(uint32_t limit, Counter::Mode mode = RESETTING, uint32_t index = 0);
uint32_t getIndex();
void increment();
float percent();
private:
bool goingForward;
uint32_t index;
const uint32_t limit;
Counter::Mode mode;
void incrementReturning();
void incrementResetting();
};
#endif
counter.cpp
#include "counter.h"
Counter::Counter(uint32_t limit, Counter::Mode mode, uint32_t index) : index(index), limit(limit), mode(mode) {
goingForward = true;
}
uint32_t Counter::getIndex() {
return index;
}
void Counter::increment() {
switch( mode ) {
case RESETTING : incrementResetting();
case RETURNING : incrementReturning();
}
}
void Counter::incrementResetting() {
index = (index + 1) % limit;
}
void Counter::incrementReturning() {
if( goingForward ) {
index++;
if( index >= limit ) {
index = limit - 1;
goingForward = false;
}
} else {
index--;
if( index <= 0 ) {
index = 1;
goingForward = true;
}
}
}
float Counter::percent() {
return (float) index / (float) limit;
}
答案 0 :(得分:4)
您的班级PeriodicEffect
有一个Counter
成员变量,没有构造函数。这意味着成员变量需要默认构造,即由没有参数的构造函数构造。你还没有提供。
您可以为Counter
提供默认构造函数,也可以让现有构造函数具有所有参数的默认值。或者,您可以使用初始化列表创建PeriodicEffect
构造函数,以便为index
提供正确的参数。
答案 1 :(得分:1)
PeriodicEffect::PeriodicEffect(
uint32_t durationMs, uint32_t periods, Counter::Mode mode) :
Runnable(), periods(periods) { /* ... */
PeriodicEffect
有一名成员Counter index;
。由于index
不在此构造函数的成员初始值设定项列表中,因此它将默认构造。
声明
index = Counter(intervalMs, mode);
构造函数内部的是赋值,而不是初始化。太晚了。