自己内部的 C++ 非静态函数指针 class

C++ non-static function pointer inside own class

我正在用 C++ 编写自己的计时器。我想知道是否可以将一个函数传递给定时器构造函数,然后再调用这个函数。

我正在考虑为此使用函数指针,但是我找不到在 class 本身内部传递非静态函数的解决方案。

G++ 给我这个错误:

Server.cpp:61:54: error: invalid use of non-static member function serverTimer = new timer::Timer(onTimerTick,3000);

我的 class Server.cpp 看起来像这样:

    private:
    void onTimerTick(){
          //do something with class variables, so can't use static? :(
      }
      public:
      Server(int port) : socket(port)
      {
          serverTimer = new timer::Timer(onTimerTick,1000);
          serverTimer->start();
      }

这是timer.h:

#ifndef TIMER_H
#define TIMER_H
namespace timer {
    class Timer{
    public:
        Timer(void (*f) (void),int interval);
        std::thread* start();
        void stop();
    private:
        int interval;
        bool running;
        void (*f) (void);
    };
}
#endif

这是timer.cpp:

#include <thread>
#include <chrono>
#include "timer.h"

timer::Timer::Timer(void (*f) (void),int interval){
    this->f = f;
    this->interval = interval;
}

std::thread* timer::Timer::start(){
    this->running = true;
    return new std::thread([this]()
    {
        while(this->running){
            this->f();
            std::this_thread::sleep_for(std::chrono::milliseconds(this->interval));
        }
    });
    //return
}

void timer::Timer::stop(){
    this->running = false;
}

对于这个问题是否有更好的解决方案,或者这是传递我的函数的错误语法? 希望有人对此有很好的解决方案。

问题是您为独立函数指定了函数指针,但您试图将其绑定到成员函数。 (非静态)成员函数确实不同:它们有一个隐藏的 this 指针需要传递给它们。

要解决这个问题,一种解决方案是使用 std::function 代替函数指针,然后将必要的代码作为 lambda 传递。

所以你的函数指针变为:

std::function<void (void)>;

你可以这样称呼它:

serverTimer = new timer::Timer([this]{onTimerTick ();},1000);