我从面向对象的角度在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();
}
}此问题发生在read()方法中的.cpp文件中。它没有看到在构造函数中创建的对象dht。我在这里错过了什么?这是在对象中拥有对象的一种良好实践吗?也许我应该将DHT库从DhtSensor类中排除在外,并在主类中创建一个DHT对象,在这个类中,我将使用库的方法将数据发送到DhtSensor
发布于 2017-04-24 20:10:32
您要在构造函数中声明'dht‘变量,这是自动分配,因此一旦离开块(在这里创建对象时),它就会消失。您应该在类规范中声明对象,然后在构造函数中初始化它。
此外,在处理对象中的对象时,请使用初始化列表here's an answer that describes the pros of doing so。
https://stackoverflow.com/questions/43596804
复制相似问题