【问题标题】:called object type 'void (B::*)(int)' is not a function or function pointer被调用的对象类型'void(B :: *)(int)'不是函数或函数指针
【发布时间】:2018-06-02 21:34:17
【问题描述】:

我试图将我的头脑围绕传递方法作为函数参数。这是一个简化的示例,它返回我不理解的编译错误

class B
{
private:
    int j;
public:
    void foo(int i){std::cout << i + this->j << std::endl;}
    void setj(int J){j=J;}
};

class A
{
private:
    B b;

public:
    void call(void (B::*fun)(int i), int i) { b.*fun(i); }
    void setBj(int j){b.setj(j);}
};


int main()
{
    A a;
    a.setBj(40);
    a.call(B::foo, 2);
}

当用

编译时
g++ -std=c++11 b.cpp -o b

我明白了

b.cpp:22:50: error: called object type 'void (B::*)(int)' is not a function or
      function pointer
        void call(void (B::*fun)(int i), int i) { b.*fun(i); }
                                                     ~~~^
b.cpp:31:12: error: call to non-static member function without an object
      argument
        a.call(B::foo, 2);
               ~~~^~~
2 errors generated.

我不明白第一条错误消息。我知道我正在调用foo,就好像它是一个静态方法一样,但我不明白如何传递一个非静态方法。

【问题讨论】:

    标签: c++ function parameter-passing


    【解决方案1】:

    两个问题。

    1. 要调用指向成员函数的指针,您需要首先应用指向成员访问运算符的指针,该指针获得可调用表达式。然后你添加一个呼叫。现在恰好.* 的优先级低于函数调用运算符。所以第一个修复:

      (b.*fun)(i)
      
    2. 只能通过在完全限定的函数名称上应用一元 &amp; 来获得指向成员函数的指针。所以第二个修复:

      a.call(&B::foo, 2);
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 2012-06-22
      • 1970-01-01
      相关资源
      最近更新 更多