将函数分配给函数指针

Assigning function to function pointer

我目前已经定义了一个函数指针,在我看来该函数与定义相匹配,但是我收到了一个错误:

1 IntelliSense: a value of type "std::string (RSSCrawler::)(const web::json::value &headlines)" cannot be assigned to an entity of type "std::string ()(const web::json::value &headlines)"

我不确定哪里出了问题,但这是我的代码

string(*GetHeadline)(const value&headlines);
GetHeadline = Extract;


string RSSCrawler::Extract(const value &headlines)
{
    return "";
}

编译器用类型不匹配错误对此进行了解释,并在第一组括号中显示了差异。你需要一个成员函数指针。这是与 'plain'/free 函数指针不同的类型。 (static 成员函数在这个意义上就像自由函数,但那不是你拥有的。)

您可以找到很多关于这些的教程,但这里是一个快速参考。 (我不得不克制自己不要将这些函数和变量名取消大写,因为它看起来不对,即使没有 SO 的自动格式化。)

// Declare pointer-to-member-function of a given class and signature
std::string (RssCrawler::* GetHeadline)(const value&);
// Bind it to any method of the same class and signature
GetHeadline = &RssCrawler::Extract;
// Call it on a given instance of said class
std::cout << (someInstance.*GetHeadline)(someValue) << std::endl; // operator .*

或者你可以这样做来获得一个 const 初始化指针,尽管我认为这违背了函数指针的目的,除了 const- 将它们声明为 [=] 的参数时的正确性21=]其他 功能...

std::string (RssCrawler::*const GetHeadline)(const value&) {
    &RssCrawler::Extract
}