指向方法问题的指针

Pointer to methods problems

嗯,正如我在问题中所说:

我的问题:msvc++ 向我抛出错误。

如果我们有:

class A 
{
    bool one, two;
    typedef void (A::* RunPtr)(int);
public:
    RunPtr Run;

    A() : one(false), two(false)
    {
        Run = &A::RunOff;
    }
    void SetOne(bool value)
    {
        one = value;
    }
    void SetTwo(bool value)
    {
        two = value;
    }
    void SetOnOrOff()
    {
        if (one || two)
            Run = &A::RunOn;
        else
            Run = &A::RunOff;
    }

    void RunOn(int param)
    {
        //RunOn stuff here
        cout << "RunOn: " << param << endl;
    }

    void RunOff(int param)
    {
        //RunOff stuff here
        cout << "RunOff: " << param << endl;
    }
};

现在我想从 class 外部调用 public Run ptr。 说:

A a = new A();
a->*Run(10);    // notice that 10 is an int

我试过两种方法:

a->Run(10)      // Option 1
a->*Run(10)     // Option 2

选项 1 抛出我

term does not evaluate to a function taking 1 arguments

选项 2 抛出我

function does not take 1 argument

这两个错误不让我调用方法指针。

使用参数调用成员Run(保存指向成员函数的指针)的正确语法是

A* a = new A();
(a->*(a->Run))(10);
               ^^^ ---------> argument(s)
     ^^^^^^^^^ -------------> class member "Run"
^^^^^^^^^^^^^^--------------> call to member function pointer syntax

// delete a after use

请注意 a 是指向 class A 的指针。您需要首先取消引用指针以访问其成员(即 a->Run)。现在您需要 call to pointer to member function pointer syntax 再次取消引用指针 a

但是,使用 std::invoke (Since ) 调用会容易得多。

#include <functional>   // std::invoke

std::invoke(a->Run, a, 10);

(See a Demo)