为函数指针分配函数 [英] Assigning function to function pointer

查看:133
本文介绍了为函数指针分配函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前定义了一个函数指针,对我来说,这个函数似乎与定义匹配,但是我得到一个错误:

I have currently defined a function pointer and to me it seems like the function matches the definition, however I am getting an error:


1 IntelliSense:不能将类型为std :: string(RSSCrawler :: )(const web :: json :: value& headlines)的值分配给类型为std :: string()(const web :: json :: value& headlines)

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)"

我不知道是什么问题,这里是我的代码

I am not sure what is wrong, but here is my code

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


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


推荐答案

类型不匹配误差并显示第一组括号中的差异。您需要一个成员函数指针。这是一个单独的类型从一个'plain'/自由函数指针。 ( static 成员函数在这个意义上就像自由函数一样,但这不是你的意思。)

The compiler explained this with a type mismatch error and showing the difference in the first set of parentheses. You need a member function pointer. That is a separate type from a 'plain'/free function pointer. (static member functions act like free functions in this sense, but that's not what you have.)

找到关于这些的大量教程,但这里是一个快速参考。 (我不得不限制自己不要去使用这些函数和变量名,因为它看起来错了,即使没有SO的自动格式化。)

You can find plenty tutorials about these, but here's a quick reference. (I have to restrain myself not to de-capitalise these function and variable names because it just looks wrong, even without SO's auto-formatting.)

// 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 初始化的指针,虽然我认为defeats的函数指针的目的除了 const -correctness时声明为参数 other functions ...

Or you can do this to get a const initialised pointer, though I think that defeats the purpose of a function pointer, except for const-correctness when declaring them as arguments to other functions...

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

这篇关于为函数指针分配函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆