c++ - 指向类方法的函数指针

标签 c++

我需要一些帮助来使用指向类中另一个类方法的函数指针,但我不确定如何让它能够调用任何类方法。

代码可能非常错误,那是因为我对它的工作原理感到很困惑,但希望这段代码能够解释我想要做什么。

#ifndef BUTTON_INPUT_HPP
#define BUTTON_INPUT_HPP

#include"../InputComponent.hpp"

class ButtonInput : public InputComponent {
public:
    template<typename C>
                            ButtonInput(void(C::*f)(), C* object);
    virtual void            update(World& world, GraphicsComponent& graphics, Actor& actor);
private:
    void (C::*func)();
};

#endif

更新函数检查按钮是否被点击,如果被点击则调用 func()。

最佳答案

这是一个简单的示例,说明如何存储指向成员函数的函数指针以及指向实例的指针。稍后可以使用 call() 调用存储的函数。

#include <iostream>

template<typename C>
class FuncHolder {
public:
    FuncHolder(void (C::*f)(), C* object) : func(f), c(object) {}
    void call() { (c->*func)(); } // Make the call.
private:
    void (C::*func)(); // Pointer to member function.
    C* c;              // Pointer to object.
};

// Example class with member function.
struct Foo {
    void test() { std::cout << "Foo" << std::endl; }
};

int main() {
    Foo foo;
    FuncHolder<Foo> f(&Foo::test, &foo);

    f.call();
}

关于c++ - 指向类方法的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21528292/

相关文章:

c++ - (C++) 将数组内容写入文件时出现问题

c++ - 将该值传递给函数时值会发生变化吗?

c++ - Windows 服务程序中退出函数的作用

c++ - 如何在 Ubuntu 上的 QT Creator 中运行 c/c++ 应用程序

c++ - 指针数组 vs ** : why does one give an error?

c++ - 算法分析——预期增长率

c++ - 添加对共享 ptr 的引用会增加引用计数吗

c++ - 使用 gdb 进行核心转储分析

c++ - 如何在 C++ 程序中包含同名的 C 系统头文件而不是 C++ 系统头文件?

c++ - 为什么 V8 的 Hello World 在 Ubuntu 上会导致段错误?