如何通过参数传递对方法的引用

时间:2016-06-08 21:54:06

标签: c++

如何通过参数传递对方法的引用?它可能看起来像这样:

class Test
{
public:
    Test();

    void Bark();
    void Bark2();

    void TakesABark( void( &method )() );
}

// Start of procedure
Test::Test()
{
    this->TakesABark(Test::Bark);        
    this->TakesABark(Test::Bark2);
}

void Test::Bark()
{
}

void Test::Bark2()
{
}

// Receives a variety of references to methods
void Test::TakesABark( void( &method )() )
{
    // Calls a third party api that would look like this:
    // Barbera::DoThatThingILike(Test::Bark2);
}

2 个答案:

答案 0 :(得分:4)

class Test
{
public:
    Test();

    void Bark();
    void TakesABark(void (Test::*method)());
};


Test::Test()
{
    this->TakesABark(&Test::Bark);
}

答案 1 :(得分:1)

示例代码:

http://coliru.stacked-crooked.com/a/9351a79c20097035

#include <iostream>
#include <string>
#include <vector>

class Test
{
public:
    Test();

    void Bark();
    void TakesABark( void(Test::*method)() );
};


Test::Test()
{
    this->TakesABark(&Test::Bark);
}

void Test::Bark()
{
    std::cout << "Bark";
}

void Test::TakesABark( void(Test::*method)() )
{
  (this->*method)();
}

int main()
{
    Test t;

}