gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:04:49 25 4
gpt4 key购买 nike

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

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com