繁体   English   中英

对象中的C ++对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM