我正在用 C++ 为 Arduino 编写一个小定时器类,但我无法通过引用正确传递它的实例而不被克隆。
这是 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
时绑定(bind).
使用 shared_ptr
例如,将为您提供与 Java 中的对象引用最接近的匹配。当然,这意味着您必须创建 Timer
你用 make_shared<Timer>()
绑定(bind)到它的对象或等效的。
使用 unique_ptr
适用于任何时候只应存在一个对计时器的引用的情况。
使用原始指针占用的内存最少,但是您必须非常小心以确保 Timer
对象在 ABC
的整个持续时间内都存在对象的生命周期,并在之后被删除。
关于c++ - Arduino C++ 将对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29357866/