[英]Creating C++ class from C, can I pass C++ objects to C++ constructor in C?
[英]Can i pass a function from a class to a constructor of another class and store it there to call later? C++
所以基本上我是在游戏中制作按钮的,这些按钮称为“按钮”。 我希望函数从中存储的类称为SoccerLevelsClass。 我尝试研究函数指针,但是我不确定这是怎么回事,尽管我认为这是正确的做法。
我想将SoccerLevelsClass的功能另存为Button的成员。 我会做这样的事情吗?
//MenuButton.h
#ifndef MenuButton
#define MenuButton
....
class Button
{
public:
Button(void(*SoccerLevelsClass::func)());
void (*SoccerLevelsClass::function)();
....
}
#endif
//MenuButton.cpp
#include <MenuButton.h>
Button::Button(void(*SoccerLevelsClass::func)())
{
function=func; //something like this
}
我知道代码可能还很遥远,但是我想知道是否有人有任何建议。 我真正想知道的是是否有可能。
是的,可以做到这一点-可以使用示例中的函数指针,也可以使用lambdas(如果可以使用C ++ 11)。
但是,由于您要调用另一个类的绑定函数,因此您也需要传递/存储指向该类实例的指针,除非该函数是静态的。
在C ++ 11中,这很简单:
std::function<void(void)> _f;
void apply() {
_f();
}
Bar(void (Foo::* f)()) {
_f = std::bind(f, Foo());
}
在C ++ 03中,这有些棘手。 请注意,在这两个版本中,我都构造了一个临时函数来调用成员函数,但是我不确定是否需要存储该类的实例。
#include <iostream>
#include <functional>
struct Foo
{
Foo() { }
void stuff() {
std::cout << "hi\n";
}
};
struct Bar
{
void (Foo::* _f)();
void apply() {
(Foo().*_f)();
}
Bar(void (Foo::* f)()) {
_f = f;
}
};
int main()
{
Bar bar(&Foo::stuff);
bar.apply();
}
对于您尝试做的事情,我将使用观察者模式:
class IFootballObserver
{
public:
virtual void OnBallKicked() = 0;
virtual ~IFootballObserver() {}
};
class Fooball
{
public:
Fooball(IFootballObserver& obs)
: mObs(obs)
{
// Call the observer interface at any time like so:
mObs.OnBallKicked();
}
private:
IFootballObserver& mObs;
};
class Button : public IFootballObserver
{
public:
// Football could be passed in/owned by something else
Button() : mFootball(*this) { }
void DoSomething()
{
// Called when foot ball is kicked
}
private:
virtual void OnBallKicked()
{
DoSomething();
}
Fooball mFootball;
};
我发现这比使用函数指针/ std :: function更容易。 另外,您可以有一个观察者向量,并通知许多事件对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.