C ++指向成员函数的指针获取错误:不是函数或函数指针

时间:2016-02-09 22:39:34

标签: c++ pointers member-function-pointers

这就是我所拥有的:

一个PostfixCalculator类,带有公共成员方法:

class PostfixCalculator
{

public:
    PostfixCalculator();

    int  top();
    int  popTop();
    void pushNum(int);
    void add();
    void minus();
    void multiply();
    void divide();
    void negate();
    bool empty();
    void pushSymbol(string);

当我尝试通过指向成员函数的指针调用成员函数时,我尝试了类似下面的内容(我知道该方法没有多大意义,它只是一个测试):

void PostfixCalculator::pushSymbol(string str)
{
    func f = &PostfixCalculator::add;
    this.*(f)();
}

但是,我收到以下编译器错误:

> postfixCalculator.cpp:84:12: error: called object type 'func' (aka
> 'void (PostfixCalculator::*)()') is not a function or function pointer
>                 this.*(f)();
>                       ~~~^ 1 error generated.

我使用clang ++编译我的程序,在fedora linux下。

2 个答案:

答案 0 :(得分:1)

首先,this是一个指针,这意味着您必须对其应用->*,而不是.*。如果您要使用.*,则必须先使用this取消引用*

其次,函数调用运算符()的优先级高于.*->*运算符,这意味着您需要额外的括号以确保首先取消引用指针f ,函数调用()应用于该解除引用的结果。

应该是

(this->*f)();

或者

(*this.*f)();

答案 1 :(得分:0)

<br>是指针,因此您应该使用this并且deref *的优先级低于函数调用->,因此您应该使用()