Arduino C++将对象作为参数传递

Arduino C++ passing objects as parameter

本文关键字:参数传递 对象 C++ Arduino      更新时间:2023-10-16

我正在为Arduino用C++编写一个小Timer类,但如果不进行克隆,我就无法通过引用正确传递它的实例。

这是计时器。h:

#ifndef Timer_h
#define Timer_h
class Timer
{
    public:
        long t = 0 ;
        long tMax = 60000 ;
        Timer() ;
        bool clocked(long n) ;
        void wait(long ms) ;
} ;
#endif

这里是Timer.cpp:

#include "Arduino.h"
#include "Timer.h"
Timer::Timer() {}
bool Timer::clocked(long n)
{
    return (t % n) == 0 ;
}
void Timer::wait(long ms)
{
    t += ms ;
    delay(ms) ;
    Serial.println(t) ;
    if (t >= tMax) t = 0 ;
}

这里有一个main.ino示例:

#include "Timer.h"
#include "ABC.h"
Timer timer = Timer() ;
ABC abc = ABC() ;
void setup()
{
    Serial.begin(9600) ;
    abc.setTimer(timer) ;
}
void loop()
{
    timer.wait(100) ;
    Serial.println(timer.t) ; // 100
    Serial.println(abc.timer.t) ; // 0, should be 100
    timer.wait(50) ;
    abc.timer.wait(100) ;
    Serial.println(timer.t) ; // 150, should be 250
    Serial.println(abc.timer.t) ; // 100, should be 250
}

以ABC.h为例:

#include "Timer.h"
class ABC
{
    public:
        Timer timer ;
        ABC() ;
        void setTimer(const Timer& tm) ;
} ;

和ABC.cpp:

#include "Timer.h"
ABC::ABC() {}
void ABC::setTimer(const Timer& tm)
{
    timer = tm ;
}

我肯定在某个地方错过了一些&*,但我不知道在哪里。

C++是一种高级语言。它支持值语义和引用语义,但是您选择通过编写以下内容来使用值语义:

Timer timer ;

在类定义中。如果您想使用引用语义,可以用Timer *timer;或智能指针(如std::shared_ptr<Timer> p_timer;std::unique_ptr<Timer> p_timer;)代替它。

使用C++引用(即Timer &timer;)是可能的,但可能不适合您的情况,因为该引用只能在创建ABC时绑定。

例如,使用shared_ptr将使您与Java中的对象引用最匹配。当然,这意味着您必须创建Timer对象,并使用make_shared<Timer>()或等效对象将其绑定到该对象。

使用unique_ptr适用于在任何时候都应该只有一个对存在的定时器的引用的情况。

使用原始指针占用的内存最少,但是您必须非常小心地确保Timer对象在ABC对象的整个生命周期内都存在,并且在这之后会被删除。