C++ pointers to member functions

2019-09-11 15:32发布

I'd like to use a pointer to member function in C++, but it doesn't work:

pointer declaration:

int (MY_NAMESPACE::Number::*parse_function)(string, int);

pointer assignation:

parse_function = &MY_NAMESPACE::Number::parse_number;

This call works perfectly (itd is an iterator to elements of a map):

printf("%s\t%p\n",itd->first.c_str(),itd->second.parse_function);

But this one doesn't work:

int ret = (itd->second.*parse_function)(str, pts);
$ error: 'parse_function' was not declared in this scope

And this one neither

int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts);
$ [location of declaration]: error: invalid use of non-static data member 'MY_NAMESPACE::Number::parse_function'
$ [location of the call]: error: from this location

I don't understant why ...

Thx in advance !!

2条回答
淡お忘
2楼-- · 2019-09-11 15:40

You can define pointers to functions like so: type(*variable)() = &function; For example:

int(*func_ptr)();
func_ptr = &myFunction;

I might just not realize your code this early morning, but problem could be that parse_function is a pointer, yet you're calling it like itd->second.*parse_function. Pointers are called with the ->*, so try doing itd->second->parse_function.

Might not fix anything tho, I can't really seem to catch onto your code. Posting more information, it's hard to tell from two lines of code.


Here's one example on how it's used in actual code, this one calls func() through cb() using pointers and parameters only:

int func()
{
    cout << "Hello" << endl;
    return 0;
}

void cb(int(*f)())
{
    f();
}

int main()
{
    int(*f)() = &func;
    cb(f);
    return 0;
}
查看更多
▲ chillily
3楼-- · 2019-09-11 15:59
int (MY_NAMESPACE::Number::*parse_function)(string, int);

This shows, parse_function is a pointer to a member function of class Number.

This call works perfectly (itd is an iterator to elements of a map):

printf("%s\t%p\n",itd->first.c_str(),itd->second.parse_function);

and from this we can see parse_function is a member of itd->second, whatever this is.

For this call

int ret = (itd->second.*parse_function)(str, pts);

or this call

int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts);

to succeed, itd->second must be of type Number, which it presumably isn't. And parse_function must be defined as either a variable in the current or enclosing scope (fist case) or a static variable of class Number (second case).

So you need some Number and apply parse_function to that

Number num;
(num.*(itd->second.parse_function))(str, pts);

or with a pointer

Number *pnum;
(pnum->*(itd->second.parse_function))(str, pts);

Update:

Since itd->second is a Number, you must apply parse_function, which is a member of it, like this

int ret = (itd->second.*(itd->second.parse_function))(str, pts);
查看更多
登录 后发表回答