C++ 如何通过指向任何类的指针从该类调用函数?

C++ 如何通过指向任何类的指针从该类调用函数?,c++,pointers,design-patterns,C++,Pointers,Design Patterns,我正在制造一台发动机。我需要创建一个Timer类,它将通过一个单独类的指针调用函数。例如: class MyTimer { public: void setTimeoutFunction( _pointer_, unsigned short timeoutMs ) { // here we need to have a opportunity to store a _pointer_ to a function } void tickTimer() {

我正在制造一台发动机。我需要创建一个
Timer
类,它将通过一个单独类的指针调用函数。例如:

class MyTimer {
public:
    void setTimeoutFunction( _pointer_, unsigned short timeoutMs ) {
        // here we need to have a opportunity to store a _pointer_ to a function
    }
    void tickTimer() {
        ...
        // here I need to call a function by a pointer
        ...
    }
};

// Main class:
class MyAnyClass {
public:
    void start() {
        MyTimer myTimer;
        myTimer.setTimeoutFunction( startThisFunc, 1500 ); // 1500ms = 1.5s
        while ( true ) {
            myTimer.tickTimer();
        }
    }
    void startThisFunc() { ... }
}

总之,如何存储指向属于某个类的函数的指针并用指针调用该函数?

在C++11中,可以使用std::function。下面是一个很好的使用指南:

我创建了一个新的代码段,其中只包含您想要的案例

#include <stdio.h>
#include <functional>
#include <iostream>

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;
};


int main()
{
  // store a call to a member function
    std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
    const Foo foo(314159);
    f_add_display(foo, 1);

    return 0;
}
#包括
#包括
#包括
结构Foo{
Foo(intnum):num_num(num){}

void print_add(int i)const{std::cout对于您的需求,我可能建议将计时器设置为类模板:

模板
结构MyTimer
{
使用FuncPtr=void(T::*)();
MyTimer(函数ptr ptr,T*obj,无符号整数超时\u ms)
:ptr_(ptr),obj_(obj),timeout_ms_(timeout_ms){
无效计时器()
{
(obj->*ptr)(;
}
函数ptr;
T*obj;
无符号整数超时\u ms;
};
用法:

struct MyAnyClass
{
    void start()
    {
        MyTimer<MyAnyClass> myTimer(&MyAnyClass::startThisFunc, this, 1500);
        while (true) { myTimer.tickTimer(); }
    }

    void startThisFunc() { /* ... */ }
};
struct MyAnyClass
{
void start()
{
MyTimer MyTimer(&MyAnyClass::startThisFunc,this,1500);
while(true){myTimer.tickTimer();}
}
void startThisFunc(){/*…*/}
};

这个问题太宽泛了,不可能得到一个好的答案,但也许你应该开始研究如何存档你想要的东西。你是一次只为一个对象设置一个专用计时器,还是一个计时器对象需要能够处理多个不同类型的对象?@KerrekSB我需要一个计时器,一次为一个对象设置一个计时器。哇,这是一个很酷的技巧。谢谢!有可能不使用关键字就使用这个示例吗?我想这是C++11风格,但不幸的是我目前不能使用C++11。这里:我找到了一个示例:
使用func=void(*)(int,int);
--类型别名,与
类型定义void(*func)(int,int);
我想这就是我需要的:)
struct MyAnyClass
{
    void start()
    {
        MyTimer<MyAnyClass> myTimer(&MyAnyClass::startThisFunc, this, 1500);
        while (true) { myTimer.tickTimer(); }
    }

    void startThisFunc() { /* ... */ }
};