我正在尝试创建一个名为Thermostat
的Arduino类,该类使用DHT
库。
我认为关于_dht
实例的声明和初始化,我可能会感到困惑。
我的目标只是清理主草图,让类Thermostat
处理与DHT相关的所有内容。
这是我的草图:
#include "Thermostat.h"
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
这是我的
Thermostat.h
文件:/*
Thermostat.h - Library for smart thermostat
*/
#ifndef Thermostat_h
#define Thermostat_h
#include "Arduino.h"
#include <DHT.h>
class Thermostat {
public:
Thermostat();
void DHTstart();
private:
DHT _dht(uint8_t, uint8_t); //// Initialize DHT sensor for normal 16mhz Arduino
};
// class initialization
Thermostat::Thermostat(){
_dht(7,DHT22);
}
void Thermostat::DHTstart(){
_dht.begin();
}
#endif
我收到以下错误:
In file included from /Users/olmo/Documents/Arduino/debug_DTH_inClass/debug_DTH_inClass.ino:2:0:
sketch/Thermostat.h: In member function 'void Thermostat::DHTstart()':
Thermostat.h:24: error: '((Thermostat*)this)->Thermostat::_dht' does not have class type
_dht.begin();
^
exit status 1
'((Thermostat*)this)->Thermostat::_dht' does not have class type
最佳答案
几乎是正确的,但是DHT _dht(uint8_t, uint8_t);
是方法原型(而不是DHT
实例)。并且您必须在构造函数的初始值设定项列表中初始化此实例:
class Thermostat {
public:
Thermostat();
void DHTstart();
private:
DHT _dht; //// Initialize DHT sensor for normal 16mhz Arduino
};
// class initialization
Thermostat::Thermostat()
: _dht(7,DHT22) // construct DHT instance with expected parameters
{ ; }
void Thermostat::DHTstart(){
_dht.begin();
}
或更短的版本:
class Thermostat {
public:
Thermostat() : _dht(7, DHT22) {;}
void DHTstart() { _dht.begin(); }
private:
DHT _dht;
};
在这种情况下(DHT类的神奇值),您可以使用c ++ 11功能(自Arduino 1.6.5起)并直接指定它,因此可以使用默认构造函数:
class Thermostat {
public:
void DHTstart() { _dht.begin(); }
private:
DHT _dht{7, DHT22};
};
关于c++ - ((Thermostat *)this)-> Thermostat::_ dht'没有类类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48366479/