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

标签 c++ pointers arduino

我正在用 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/

相关文章:

c - 为什么指针在此处被类型转换为 char?

arduino - 在 AVR Studio 中使用自动完成功能通过 avr-gcc 编码 C

Arduino超声波传感器总是返回0

c - 在 C 中给定开始和结束内存地址的意外行为遍历数组

c++ - 在 C++ 中,迭代器失效规则是否也适用于所有标准容器的指针?

android - 使用wifi Shield将arduino连接到android

c++ - 每当按下按钮时,如何在 Qt tableView 中自动选择下一行?

c++ - 编译器如何为这个结构分配内存?

c++ - 在 GStreamer 管道总线上调用 gst_bus_set_sync_handler 是否安全?

c++ - 如何使用模板函数减去两个对象?