成员函数的C ++指针 [英] C++ pointers to member functions

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

问题描述

我想在C ++中使用指向成员函数的指针,但不起作用:

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

指针声明:

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

指针分配:

parse_function = &MY_NAMESPACE::Number::parse_number;

这个调用非常合适(itd是映射元素的迭代器):

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

但这不起作用:

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

/ p>

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。

推荐答案

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

这表明, parse_function Number 的成员函数。

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 \\\
,itd-> first.c_str(),itd-> second.parse_function);

code> parse_function 是 itd-> second 的成员,无论是什么。

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

对于此调用

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

或此通话

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

成功, itd->秒必须是 Number 类型,它可能不是。而parse_function必须定义为当前或封闭范围(第一种情况)中的变量或类型为Number(第二种情况)的静态变量。

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

Number 并将 parse_function 应用于

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

或指针

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

更新

由于 itd-> second 是数字,您必须应用 parse_function 成员,例如

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

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

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