从 C++ 中的另一个对象执行方法 [英] Method execution from another object in C++

查看:58
本文介绍了从 C++ 中的另一个对象执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先请允许我介绍一下我的类结构.我正在为 ARM 设备 (STM32) 设计一个小库,我想实现几个对象来定义系统上可用的不同外设.

First of all allow me to introduce a little bit of my class structure. I am designing a little library for an ARM device (STM32) and I want to implement a couple of objects defining the different peripheral available on the system.

class xGPIO : public Peripheral 
{
public:
    xGPIO();
    xGPIO(GPIO_TypeDef * GPIOx1, uint16_t Pinx1);
    virtual ~xGPIO();

    void on(void);
    void off(void);
private:
    void xInitGPIO(void);

};

我的想法是实现一个名为 callback 的内部公共函数,它设置下一个要在我的计时器对象上调用的函数.然而,这个函数肯定是在另一个类中定义的方法,我希望它从 xTimer 执行.这里的行为应该是,每当 Timer 结束倒计时,它应该调用程序员在 callBack 方法中存储的函数.

The idea I have in mind is to implement an internal public function named callback which sets which function is the next to be called on my timer object. However this function will for sure be a method defined in another class and I want it to be executed from xTimer. The behaviour here, should be that whenever the Timer ends its countdown, it should call the function stored by the programmer in the callBack method.

class xTimer : public Peripheral 
{
public:
    xTimer(TIM_TypeDef * tim);
    virtual ~xTimer();
    /* void callBack(void (*f)()); */

private:
    void xInitTimer(void);
    TIM_HandleTypeDef htim;
};

void xTimer::callBack(void (*f)())
{
   f();
}

main.cpp下的代码如下:

The code under main.cpp woudl be as follows:

int main(void)
{
    mySYS->initialize(false);

    xGPIO myGreenLed (GPIOB, GPIO_PIN_0);

    /* Declare Timers.  */
    xTimer myTimer(TIM2);    
    // myTimer.callBack(myGreenLed.on);
}

有关如何解决此问题的任何线索?是否有一种简单的方法可以在 C++ 程序上遵守该设计?

Any clues on how to solve this issue? Is there an easy way to comply with that design on a C++ program?

推荐答案

您正在使用 C 模式.C++ 有更强大的std::function.你的 xTimer::callBack 应该定义为

You're using C patterns. C++ has the far more powerful std::function. Your xTimer::callBack should be defined as

void xTimer::callBack(std::function<void(void)> f) { f(); }

所以它可以被称为

myTimer.callBack([&](){myGreenLed.on()}); //using lambda

myTimer.callBack(std::bind(&xGPIO::on, &myGreenLed));

这篇关于从 C++ 中的另一个对象执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆