您应该阅读静态成员函数以及成员函数指针。有三种方法可以解决您的问题。
首先是制作Coin::Flip
一个静态成员函数:
#include <string>
#include <iostream>
typedef std::string (*Flipper)(); // Function pointer typedef
class Coin
{
public:
Coin() {}
// Static member function. A pointer to a static member function can be
// held in a regular function pointer.
static std::string Flip ()
{
srand(23);
int side = rand() % 2 + 1;
return (side == 1) ? "heads." : "tails.";
}
};
std::string Flip(Flipper flipper)
{
return flipper();
}
int main()
{
std::cout << "Flipping a coin..." << std::endl;
std::string output = Flip(&Coin::Flip);
std::cout << "The coin came up " << output << std::endl;
return 0;
}
如果Coin::Flip
需要是一个非静态成员函数,你可以传递一个Coin
实例Flip
,连同成员函数指针:
#include <functional>
#include <string>
#include <iostream>
class Coin
{
public:
Coin() {}
// Non-static member function.
std::string Flip ()
{
srand(23);
int side = rand() % 2 + 1;
return (side == 1) ? "heads." : "tails.";
}
};
typedef std::mem_fun_ref_t<std::string, Coin> Flipper;
// We need the Coin instance as well as the member function pointer.
std::string Flip(Coin& coin, Flipper flipper)
{
// Invoke the flipper member function on the coin instance
return flipper(coin);
}
int main()
{
// Since we're using a non-static member function, we need an instance
// of Coin.
Coin coin;
std::cout << "Flipping a coin..." << std::endl;
std::string output = Flip(coin, mem_fun_ref(&Coin::Flip));
std::cout << "The coin came up " << output << std::endl;
return 0;
}
最后,如果Flipper
函子可以是来自任何类型对象(不仅是 Coin)的成员函数,并且您不希望Flip
自由函数成为模板,那么您将需要std::function
并且std::bind
这是最近 C++11 的一部分标准。std::function
是一个通用的多态函数包装器,适用于任何类型的可调用目标:自由函数、成员函数、函数对象等。如果你不能使用 C++11,Boost 库有等价物boost::function
和boost::bind
.
#include <functional>
#include <string>
#include <iostream>
class Coin
{
public:
Coin() {}
// Non-static member function.
std::string Flip ()
{
srand(23);
int side = rand() % 2 + 1;
return (side == 1) ? "heads." : "tails.";
}
// Static member function.
static std::string StaticFlip()
{
srand(23);
int side = rand() % 2 + 1;
return (side == 1) ? "heads." : "tails.";
}
};
// Flipper is a generic function object wrapper that works with free functions,
// function objects, static member functions, and non-static member functions.
typedef std::function<std::string ()> Flipper;
std::string Flip(Flipper flipper)
{
return flipper();
}
int main()
{
// Example with non-static member function
Coin coin;
// Bind a Coin instance along with a Coin::Flip member function pointer.
Flipper flipper1 = std::bind(&Coin::Flip, &coin);
std::cout << "Flipping a coin..." << std::endl;
std::string output = Flip(flipper1);
std::cout << "The coin came up " << output << std::endl;
// Example with static member function
Flipper flipper2 = &Coin::StaticFlip;
std::cout << "Flipping a coin..." << std::endl;
output = Flip(flipper2);
std::cout << "The coin came up " << output << std::endl;
return 0;
}