问题
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: 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 "";
}
回答1:
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.)
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 .*
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
}
来源:https://stackoverflow.com/questions/38410037/assigning-function-to-function-pointer