首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对象中的C++对象

对象中的C++对象
EN

Stack Overflow用户
提问于 2017-04-24 20:04:29
回答 1查看 2.6K关注 0票数 3

我从面向对象的角度在C++中为Arduino编写了一个程序,遇到了一个问题:类的方法无法看到该类的构造函数中定义的对象。我试图完成的是创建一个对象(类),用于容纳用于计算和输出来自DHT11传感器的数据的各种方法。完整代码:

代码语言:javascript
复制
* 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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-24 20:10:32

您要在构造函数中声明'dht‘变量,这是自动分配,因此一旦离开块(在这里创建对象时),它就会消失。您应该在类规范中声明对象,然后在构造函数中初始化它。

此外,在处理对象中的对象时,请使用初始化列表here's an answer that describes the pros of doing so

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43596804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档