Subclass调用Base Class构造函数然后使用子类Arduino C ++中的Base类的实例方法

时间:2015-07-17 20:16:54

标签: c++ oop inheritance arduino

我有一个基类FCBRelay,在该类中,它处理将继电器设置到引脚并保留一般方法,例如ononForTime

当我尝试在子类中调用onForTime时,它不会编译给出错误:

cannot call member function 'void FCBRelay::onForTime(int)' without object

现在我理解错误是什么,因为onForTime方法不是 static ,但是我的Subclass构造函数也调用了Base Class构造函数。或者说是我的理解。

这个想法是在我的main函数中更具描述性。而不是致电waterPump.onForTime(2);我可以致电waterPump.squirt(2);

我的课程如下

FCBRelay.h

#ifndef FCBRelay_H
#define FCBRelay_H

#include <Arduino.h>

class FCBRelay {
  public:
    FCBRelay(int pinNo);

    int delayTime;

    void tick();
    void onForTime(int timeInSeconds);

  private:
    int _pinNumber;
    int _lastTickMillis;

    void on();
    void off();
};

#endif

FCBRelay.cpp

#include "FCBRelay.h"

FCBRelay::FCBRelay(int pinNo) {
  _pinNumber = pinNo;
  pinMode(_pinNumber, OUTPUT);
}

void FCBRelay::onForTime(int timeInSeconds) {
  delayTime = timeInSeconds * 1000;
  on();
}

void FCBRelay::tick() {
  unsigned long currentMillis = millis();
  if((currentMillis - _lastTickMillis) >= delayTime) {
      _lastTickMillis = currentMillis;
      off();
  }
}

void FCBRelay::on() {
  digitalWrite(_pinNumber, HIGH);
}

void FCBRelay::off() {
  digitalWrite(_pinNumber, LOW);
}

FCBWaterPump.h

#ifndef FCBWaterPump_H
#define FCBWaterPump_H

#include "FCBRelay.h"

class FCBWaterPump : public FCBRelay {
  public:
    FCBWaterPump(int pinNo);

    void squirt(int timeInSeconds);
};

#endif

FCBWaterPump.cpp

#include "FCBWaterPump.h"

FCBWaterPump::FCBWaterPump(int pinNo) : FCBRelay(pinNo) {

}

void squirt(int timeInSeconds) {
  FCBRelay::onForTime(timeInSeconds);
}

任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:4)

你不小心写了一个独立的功能。这就是没有对象的原因。

改变这个:

void squirt(int timeInSeconds) {
  FCBRelay::onForTime(timeInSeconds);
}

到此:

void FCBWaterPump::squirt(int timeInSeconds) {
//   ^^^^^^^^^^^^^^
  FCBRelay::onForTime(timeInSeconds);
}