2017-04-24 114 views
1

我從OOP的角度爲C++寫了一個Arduino的程序,並遇到了一個問題:類的方法無法看到該類的構造函數中定義的對象。我試圖完成的是創建一個對象(類),用於容納各種用於計算和輸出來自傳感器的數據的方法。 全碼:對象內的C++對象

* 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

+1

您可能想讓實例成爲您的類的成員,而不是函數的一部分。 – JVApen

+1

在開始使用一種語言之前,你確實需要閱讀一本關於C++的書。使用C++進行嘗試和錯誤是非常痛苦的,通常不會帶來好的結果。 – SergeyA

回答

5

你正在構造函數中聲明你的'dht'變量,這是自動分配,所以一旦剩下塊就會消失(這是當你在這裏創建對象時)。您應該在您的類規範中聲明對象,然後在構造函數中初始化它。

另外,使用對象內的對象時,請使用初始化列表here's an answer that describes the pros of doing so

+0

謝謝!我不敢相信我沒有注意到這樣一個明顯的錯誤! – Justin