如何调用成员函数指针? [英] How do I call a member function pointer?

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

问题描述

我在Ubuntu 12.04 LTS 32位上使用带有GNU工具链的C ++ 11。我知道有人问过类似的问题,但是我还没有找到确切的问题,也无法从已经发布的内容中得到任何有用的信息,所以去了:

I am using C++11 with GNU tool chain on Ubuntu 12.04 LTS 32 bit. I know similar questions have been asked, but I haven't found exactly this one, and I wasn't able to get anything that worked from what is already posted, so here goes:

我有这样的代码:

enum class FUNC_TYPES { FUNCTYPE_1,FUNCTYPE_2,FUNCTYPE_3};

class AClass
{
...

typedef void (AClass::* TFunc )( );
std::map<FUNC_TYPES, TFunc> mFuncMap;


void doStuff();

....

}

我像这样初始化mFuncMap:

I initialize mFuncMap like this:

void AClass::initFuncMap( )
{
    mFuncMap[FUNC_TYPES::FUNCTYPE_1] = & AClass::doStuff;
}

所有编译正常。

现在我想调用映射的函数指针。

Now I want to call the mapped function pointer.

我尝试了这种形式,我知道这种形式适用于非成员函数的函数指针。

I tried this form, which I know works for function pointers that are not for member functions.

mFuncMap[FUNC_TYPES::FUNCTYPE_1]( );

这会产生很长的解释性编译器错误:

This generates a very long explanatory compiler error:


错误:必须使用'。'或'-> '来调用
(AClass *)this)->中的指针成员函数AClass :: mFuncMap.std :: map< _Key,_Tp,_Compare,
_Alloc> ...

error: must use ‘.’ or ‘->’ to call pointer-to-member function in (AClass*)this)->AClass::mFuncMap.std::map<_Key, _Tp, _Compare, _Alloc>...

我尝试过我可以想到的几乎每种形式的解引用都是从搜索中找到的-带括号,没有括号等等等。但是我无法正确地进行此调用。

I tried just about every form of de-referencing I can think of and that I found from searching around - with parenthesis, without them, etc. etc. etc... but I cannot get the syntax right to make this call.

调用映射成员函数的正确语法是什么?我的声明或初始化是否有问题,导致此问题?

What is the correct syntax for calling the mapped member function? Is there something wrong with my declaration or initialization that is causing this problem?

推荐答案

这与地图无关,也与地图无关与typedefs有关。 您拥有一个指向成员函数的指针,并且

This has nothing to do with maps, and nothing to do with typedefs. You have a pointer-to-member-function and you're not invoking it properly.

您需要 AClass 才能在以下位置运行该功能:

You need an AClass to run the function on:

AClass& a = someAClassSomewhere();
(a.*(mFuncMap[FUNC_TYPES::FUNCTYPE_1]))();

当然这确实很丑陋,所以请提前考虑绑定对象:

Of course this is really ugly, so consider binding the object ahead of time:

typedef std::function<void()> TFunc;
std::map<FUNC_TYPES, TFunc> mFuncMap;

// ...

mFuncMap[FUNC_TYPES::FUNCTYPE_1] = std::bind(&AClass::doStuff, this);

// ...

mFuncMap[FUNC_TYPES::FUNCTYPE_1]();

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

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