[英]C++ object within object
我從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();
}
}
該問題發生在.cpp文件的read()
方法內。 它看不到在構造函數中創建的對象dht
。 我在這里想念什么? 將對象包含在對象中甚至是一種好習慣嗎? 也許我應該從DhtSensor
類中排除DHT
庫,並在主類中創建DHT
對象,在該類中我將使用庫的方法將數據發送到DhtSensor
?
您在構造函數中聲明了“ dht”變量,它是自動分配的,因此一旦離開該塊(在此處創建對象時),它將消失。 您應該在類規范中聲明您的對象,然后在構造函數中對其進行初始化。
另外,在對象中使用對象時,請使用初始化列表, 這是描述這樣做的優點的答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.