调用成员函数指针 [英] Calling Member Function Pointers

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

问题描述

我在调用结构内部的函数指针时遇到麻烦.我在类之外使用过这种方法,但现在我正在使用指向其他类方法的函数指针的类方法中尝试使用此方法....我收到了编译器错误.这是我的课程:

I am having trouble calling a function pointer inside a structure. I have used this approach before outside of classes, but now that I am trying it inside a class method using function pointers to other class methods.... I am receiving a compiler error. Here is my class:

class Myclass
{
    int i;

    void cmd1(int)
    {}

    void cmd2(int)
    {}

    void trans()
    {
        const struct
        {
            std::string cmd;
            void (Myclass::*func)(int)
        }
        CmdTable[] =
        {
            { "command1", &Myclass::cmd1 },
            { "command2", &Myclass::cmd2 }
        };

        CmdTable[0].func(i);
        CmdTable[1].func(i);
    }
};

CmdTable[0].func(i);CmdTable[1].func(i);都提供以下内容 错误: 错误:表达式必须具有(指向指针的)函数类型.

The lines CmdTable[0].func(i); and CmdTable[1].func(i); both provide the following error: Error: expression must have (pointer-to-) function type.

我意识到这样做的方法可能更好,但是我很好奇为什么我写的东西行不通.任何解释将不胜感激.

I realize there are probably better ways of doing this, but I'm rather curious as to why what I've written doesn't work. Any explanation would be greatly appreciated.

推荐答案

成员函数的指针是纯 class 属性.您需要将其与类实例结合才能进行有意义的函数调用.例如,要使用实例*this,可以使用运算符->*并说:

The pointer-to-member-function is a pure class property. You need to combine it with a class instance in order to make a meaningful function call. For example, to use the instance *this, you can use the operator ->* and say:

(this->*CmdTable[0])(i);

或者您可以在对象值上使用运算符.*:

Or you can use operator .* on an object value:

(*this.*CmdTable[0])(i);

后一种形式总是正确的.对于前者,请注意operator->*可能会过载,并且执行无关的操作.

The latter form is always correct. For the former, note that operator->* may be overloaded and do something unrelated.

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

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