簡體   English   中英

C ++非自定義函數指針在自己的類中

[英]C++ non-static function pointer inside own class

我正在用c ++編寫自己的計時器。 我想知道是否可以將函數傳遞給計時器構造函數並稍后調用此函數。

我正在考慮為此使用函數指針,但是我找不到在類本身內部傳遞非靜態函數的解決方案。

G ++給了我這個錯誤:

Server.cpp:61:54:錯誤:無效使用非靜態成員函數serverTimer = new timer :: Timer(onTimerTick,3000);

我的類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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM