Arduino C++将对象作为参数传递
Arduino C++ passing objects as parameter
我正在为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
对象的整个生命周期内都存在,并且在这之后会被删除。
相关文章:
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 如何将对象数组作为参数传递给模板
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 对象作为参数传递,就好像我们正在传递构造函数值一样
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 将对象作为参数传递,没有可行的重载"="
- 当我按值传递参数时对象被破坏时?
- 在将匿名对象作为参数传递时,不会调用任何构造函数
- 是否可以创建一个指向对象的智能指针并将此智能指针作为参数传递给构造函数?
- C++:将对象作为参数传递
- 将 std::ofstream 对象作为参数传递给类方法
- 将对象向量的指针作为参数传递,但差异更大
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何将对象作为参数传递
- 将对象作为C 中的参数传递
- 将新对象的名称作为参数传递
- 将对象数组作为参数传递的最佳方法是什么
- 为什么将临时对象作为参数传递需要 std::move?
- 将任何数据类型/对象作为参数传递以确定其大小