2017-04-24 117 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