C++函数指针(类成员)到非静态成员函数

Gir*_*ish 39 c++ function-pointers

class Foo {
public:
    Foo() { do_something = &Foo::func_x; }

    int (Foo::*do_something)(int);   // function pointer to class member function

    void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; }

private:
    int func_x(int m) { return m *= 5; }
    int func_y(int n) { return n *= 6; }
};

int
main()
{
    Foo f;
    f.setFunc(false);
    return (f.*do_something)(5);  // <- Not ok. Compile error.
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它发挥作用?

Nic*_*kis 36

 class A{
    public:
        typedef int (A::*method)();

        method p;
        A(){
            p = &A::foo;
            (this->*p)(); // <- trick 1, inner call
        }

        int foo(){
            printf("foo\n");
            return 0;
        }
    };

    void main()
    {
        A a;
        (a.*a.p)(); // <- trick 2, outer call
    }
Run Code Online (Sandbox Code Playgroud)


Jam*_*ran 32

你想要的线是

   return (f.*f.do_something)(5);
Run Code Online (Sandbox Code Playgroud)

(编译 - 我试过了)

" *f.do_something"指的是指针本身---"F"告诉我们哪里得到do_something值.但是当我们调用函数时,我们仍然需要给出一个将成为this指针的对象.这就是我们需要" f."前缀的原因.

  • 从技术上讲,"f.do_something"返回指针,".*"运算符调用类的指针到成员函数. (8认同)