我正在从OOP角度编写一个用于C++的Arduino程序并遇到一个问题:类的方法无法看到该类的构造函数中定义的对象.我试图完成的是创建一个对象(类),用于容纳各种方法,这些方法用于计算和输出DHT11传感器的数据.完整代码:
* DhtSensor.h
*
* Created on: 2017-04-18
* Author: Secret
*/
#ifndef DhtSensor_h
#define DhtSensor_h
class DhtSensor {
public:
DhtSensor(int dhtPin); //constructor
void read();
void printToScreen(); //a method for printing to LCD
private:
unsigned long previousMillis; //Millis() of last reading
const long readInterval = 3000; //How often we take readings
float readingData[2][30]; //store current ant last values of temperature [0] and humidity [1] readings
int readingIndex;
bool initDone; //Bool value to check if initialization has been complete (Array full)
float totalTemp;
float totalHumidity;
float avgTemp;
float avgHumidity;
float hic; //Heat Index
};
#endif
/*
* DhtSensor.cpp
*
* Created on: 2017-04-18
* Author: Secret
*/
#include "DhtSensor.h"
#include "DHT.h"
#include "Arduino.h"
DhtSensor::DhtSensor(int dhtPin){
DHT dht(dhtPin,DHT11);
dht.begin();
previousMillis = 0;
totalTemp = avgTemp = 0;
totalHumidity = avgHumidity = 0;
hic = 0;
readingIndex = 0;
initDone = false;
for(int i = 0; i<2; i++){ //matrix init
for(int j=0; j<30; j++){
readingData[i][j]=0;
}
}
}
void DhtSensor::read(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= readInterval){
readingData[0][readingIndex] = dht.readTemperature();
}
}
Run Code Online (Sandbox Code Playgroud)
该问题发生read()在.cpp文件中的方法中.它没有看到dht构造函数中创建的对象.我在这里错过了什么?在对象中包含对象这是一个很好的做法吗?也许我应该DHT从DhtSensor类中排除库并DHT在主类中创建一个对象,我将使用库的方法将数据发送到DhtSensor?
小智 5
你在构造函数中声明了你的'dht'变量,这是自动分配,所以一旦剩下这个块就会消失(这就是你的对象在这里创建的时候).您应该在类规范中声明对象,然后在构造函数中初始化它.
此外,在处理对象中的对象时,请使用初始化列表,这是一个描述这样做的优点的答案.