来自类的计时计时器类传递方法不起作用

问题描述

我正在尝试从tutorialspoint使用代码,但是当我要将函数放在类中时遇到了问题。

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later {
   public:
      template <class callable,class... arguments>
      later(int after,bool async,callable&& f,arguments&&... args){
      std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f),std::forward<arguments>(args)...));
      if (async) {
         std::thread([after,task]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
         }).detach();
      } else {
         std::this_thread::sleep_for(std::chrono::milliseconds(after));
         task();
      }
   }
};
void test1(void) {
   return;
}

int main() {
   later later_test1(3000,false,&test1);
   later later_test2(1000,&test2,75);
   later later_test3(3000,101);
}

我想将函数test1放在同一个类中,还是要定义一个新的类。问题是代码无法编译。

 #include <functional>
    #include <chrono>
    #include <future>
    #include <cstdio>
    class later {
       public:
          template <class callable,class... arguments>
          later(int after,arguments&&... args){
          std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f),std::forward<arguments>(args)...));
          if (async) {
             std::thread([after,task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
             }).detach();
          } else {
             std::this_thread::sleep_for(std::chrono::milliseconds(after));
             task();
          }
       }

    void test1(void) {
       return;
    }
    };
int main() {
   later later_test1(3000,&later::test1);
   later later_test2(1000,101);
}    

解决方法

在第二段代码中,test1是后面的非静态成员函数。这意味着它需要一个对象才能被调用。

将其设为静态:

    static void test1(void) {
       return;
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...