开发者

How to add event listners / signals to a simple superman class?

开发者 https://www.devze.com 2023-02-03 00:07 出处:网络
I can and would love to use boost or std for this. Sorry - I am new开发者_如何学运维 to C++. So I created a really simple program like:

I can and would love to use boost or std for this. Sorry - I am new开发者_如何学运维 to C++. So I created a really simple program like:

#include <iostream>
#include <string>
using namespace std;

class superman
{
public:
  void punch(){cout << "superman: I hit the bad guy!" << endl;};
};

int main()
{
  superman clark;
  clark.punch();
  cin.get();
}

I want to add an event listner that would tell me when clark punched and cout something like "superman punched!". How to add such event listner and event function to my class?


you can use boost::signal for that

you have to declare one class and overload her operator () after uoi have to bind the class on the signal, by using connect() method, and finally, use operator () of the signal

struct HelloWorld 
{
  void operator()() const 
  { 
    std::cout << "Hello, World!" << std::endl;
  } 
};

// ...

// Signal with no arguments and a void return value
boost::signal<void ()> sig;

// Connect a HelloWorld slot
HelloWorld hello;
sig.connect(hello);

// Call all of the slots
sig();

for using parameter in slot:

void print_sum(float x, float y)
{
  std::cout << "The sum is " << x+y << std::endl;
}

boost::signal<void (float, float)> sig;

sig.connect(&print_sum);

sig(5, 3);
0

精彩评论

暂无评论...
验证码 换一张
取 消