C++;自身类内的非静态函数指针 我在C++中编写自己的计时器。我想知道是否可以将函数传递给计时器构造函数,然后稍后调用此函数

C++;自身类内的非静态函数指针 我在C++中编写自己的计时器。我想知道是否可以将函数传递给计时器构造函数,然后稍后调用此函数,c++,c++11,timer,static,function-pointers,C++,C++11,Timer,Static,Function Pointers,我曾经考虑过使用函数指针,但是我找不到在类内部传递非静态函数的解决方案 G++给了我这个错误: Server.cpp:61:54:错误:非静态成员函数的使用无效 serverTimer=新计时器::计时器(onTimerTick,3000) My class Server.cpp如下所示: private: void onTimerTick(){ //do something with class variables, so can't use static?

我曾经考虑过使用函数指针,但是我找不到在类内部传递非静态函数的解决方案

G++给了我这个错误:

Server.cpp:61:54:错误:非静态成员函数的使用无效 serverTimer=新计时器::计时器(onTimerTick,3000)

My 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();
      }
serverTimer = new timer::Timer([this]{onTimerTick ();},1000);
这是定时器。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;
}
#包括
#包括
#包括“timer.h”
计时器::计时器::计时器(无效(*f)(无效),整数间隔){
这个->f=f;
这个->间隔=间隔;
}
std::thread*timer::timer::start(){
此->运行=真;
返回新的std::thread([this]()
{
当(此->运行时){
这个->f();
std::this_thread::sleep_for(std::chrono::毫秒(this->interval));
}
});
//返回
}
无效计时器::计时器::停止(){
此->运行=错误;
}
是否有更好的解决方案来解决这个问题,或者这是传递函数的错误语法?
希望有人对此有一个很好的解决方案。

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

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

因此,函数指针变为:

std::function<void (void)>;

查找
std::function
。您需要的是
委托
。只为C++和委托搜索堆栈溢出,你会发现成千上万页;BitTickler,delegate是一个可怕的词,它来自于禁止使用指针的语言,因此不能使用普通的“函数指针”。请注意,您应该使用
std::atomic running
,并且返回
std::thread*
也是可疑的。@SergeyA语言很有趣,不是吗?在C++环境中,术语“委托”具有特殊的意义。它不仅仅是“函数指针”。因此,如果它在其他上下文中使用,其他含义对它在C++上下文中的使用也不多。它是有效的:)lambda是[this]{onTimerTick();}在简单的情况下,我个人更喜欢
std::bind
。注意:当你有一个类,它有一个std::function对象,其中嵌入了指向自身的this指针时,最好使该类不可复制,因为复制语义是不正确的。