由“using”声明的函数指针的别名

Tra*_*ter -1 c++ using function-pointers state-machine

我已经用“using”关键字声明了函数指针的别名,但我不知道如何使用该别名。

在类UpdateState的函数中Person,我想替换m_state与当前状态和要转换到下一个状态相对应的函数的返回值。但是,以下错误发生在第 38 行Person.cpp,我不知道如何纠正该行。我认为我错误地使用了别名数组。

error C2064: term does not evaluate to a function taking 1 arguments
Run Code Online (Sandbox Code Playgroud)

人.h

error C2064: term does not evaluate to a function taking 1 arguments
Run Code Online (Sandbox Code Playgroud)

人物.cpp

#pragma once

enum STATE
{
    A,
    B,
    C,
    D,
    E,
    STATE_NUM,
};

class Person
{
public:
    Person();
    ~Person();
    void UpdateState();
    STATE IsInStateA(char nextState);
    STATE IsInStateB(char nextState);
    STATE IsInStateC(char nextState);
    STATE IsInStateD(char nextState);
    STATE IsInStateE(char nextState);
private:
    STATE m_state;
};
Run Code Online (Sandbox Code Playgroud)

use*_*570 6

要获取指向非静态成员的指针,语法为&ClassName::membername

此外,使用指向成员函数的指针的调用是使用 或 进行.*->*

下面是修改后的工作示例,其中我添加了注释以显示我所做的更改:

void Person::UpdateState()
{
    char inputArray[] = { 'a','b','c','d','e' };
    char nextStateInput;
    while (1) {
        std::cout << "Please input the state you want to transition to next: ";
        std::cin >> nextStateInput;
        for (int i = 0; i < sizeof inputArray / sizeof inputArray[0]; ++i) {
            if (nextStateInput == inputArray[i]) {
                break;
            }
        }
        std::cout << "Please enter one of the letters a-e." << std::endl;
    }
    using StateFunc = STATE(Person::*)(char);
    StateFunc stateFuncTable[STATE_NUM] = {
        &Person::IsInStateA,       //added &Person:: here
        &Person::IsInStateB,       //added &Person:: here 
        &Person::IsInStateC,       //added &Person:: here
        &Person::IsInStateD,       //added &Person:: here
        &Person::IsInStateE        //added &Person:: here
    };;

    for (int i = 0; i < STATE_NUM; ++i) {
        if (nextStateInput == inputArray[i]) {
//---------------------vvvvvvv---------------------->correct syntax using ->*
            m_state = (this->*stateFuncTable[m_state])(nextStateInput);  
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

工作演示


对于 C++17,您可以使用std::invoke而不是->*如下所示:

m_state = std::invoke(stateFuncTable[m_state], this, nextStateInput);
Run Code Online (Sandbox Code Playgroud)

演示 C++17

  • 添加到此,有关更详细的概述,请参阅此处的“指向成员函数的指针”部分:https://en.cppreference.com/w/cpp/language/pointer (2认同)