【问题标题】:I was following a Udemy class but the code isnt working [duplicate]我正在关注 Udemy 课程,但代码不起作用 [重复]
【发布时间】:2017-08-26 10:11:38
【问题描述】:
C:\Users\hp\Desktop\Timer.h|77|error: no matching function for call to 
'std::thread::thread(<unresolved overloaded function type>, Timer* const)'|

这是我尝试构建时遇到的错误,我正在学习 Udemy 课程,我对 C++ 了解不多,如果有人可以提供帮助,谢谢! 整个项目的代码也可以在github上找到:https://github.com/creator69/keylogger-

它给出错误的代码:

#ifndef TIMER_H
#define TIMER_H

#include <chrono>
#include <thread>

class Timer {

    std::thread Thread;

    bool Alive = false;

    long CallNumber = -1L;

    long repeat_count = -1L;

    std::chrono::milliseconds interval = std::chrono::milliseconds(0);

    std::function<void(void)> funct = nullptr;

    void SleepAndRun() {

        std::this_thread::sleep_for(interval);
        if (Alive)
            Function()();
    }

    void ThreadFunc() {

        if (CallNumber == Infinite)
            while (Alive)
                SleepAndRun();
        else

            while (repeat_count--)
                SleepAndRun();
    }

  public:
    static const long Infinite = -1L;

    Timer() {}

    Timer(const std::function<void(void)> &f) : funct(f) {}

    Timer(const std::function<void(void)> &f, const unsigned long &i, const long repeat = Timer::Infinite)
            : funct(f), interval(std::chrono::milliseconds(i)), CallNumber(repeat) {}

    void Start(bool Async = true) {

        if (IsAlive())
            return;

        Alive = true;

        repeat_count = CallNumber;

        if (Async)
            Thread = std::thread(ThreadFunc, this);
        else
            this->ThreadFunc();
    }

    void Stop() {

        Alive = false;

        Thread.join();
    }
    void SetFunction(const std::function<void(void)> &f) { funct = f; }
    bool IsAlive() const { return Alive; }
    void RepeatCount(const long r) {

        if (Alive)
            return;
        CallNumber = r;
    }

    long GetLeftCount() const { return repeat_count; }

    long RepeatCount() const { return CallNumber; }
    void SetInterval(const unsigned long &i) {

        if (Alive)
            return;
        ;

        interval = std::chrono::milliseconds(i);
    }

    unsigned long Interval() const { return interval.count(); }

    const std::function<void(void)> &Function() const { return funct; }
};

#endif

【问题讨论】:

    标签: c++ stdthread


    【解决方案1】:
    Thread = std::thread(ThreadFunc, this);
    

    将指向成员函数的指针传递给std::thread的构造函数的正确方法是:

    Thread = std::thread(&Timer::ThreadFunc, this);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 2022-07-07
      相关资源
      最近更新 更多