【问题标题】:C++ pointer to member function getting an error : not a function or function pointer指向成员函数的 C++ 指针出错:不是函数或函数指针
【发布时间】:2016-02-09 22:39:33
【问题描述】:

这是我所拥有的:

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

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

【问题讨论】:

  • 你用的是什么func
  • 离题:看看std::bindstd::function。它们自动化并隐藏了大部分令人讨厌的东西。

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


【解决方案1】:

首先,this 是一个指针,这意味着你必须对它应用->*,而不是.*。如果要使用.*,则必须先将this* 解引用。

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

应该是

(this->*f)();

或者

(*this.*f)();

【讨论】:

    【解决方案2】:

    this是一个指针,所以你应该使用->和deref *的优先级低于函数调用(),所以你应该使用(this->*f)()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多