状态机、子类和函数指针

State Machines, Sub-Classes, and Function Pointers

本文关键字:函数 指针 子类 状态机      更新时间:2023-10-16

我在实现类的状态机时遇到问题。我不断收到错误:

state.cpp:5: error: have0 was not declared in this scope 
state.cpp:10: error: redefinition of State* Have0State::process(std::string)
state.h:18: error: virtual State* Have0State::process(std::string) previously defined here

在继续使用机器的其他部分之前,我正在尝试让Have0State正常工作,因此产生了稀疏代码。

state.h:

#ifndef STATE_H
#define STATE_H
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>

class State{
    public:
        State(){};
        virtual State* process(std::string input) = 0;

};
class Have0State: public State {
    public:
        Have0State():State(){};
        virtual State* process(std::string input);
}have0;
#endif

state.cpp:

#include "state.h"
using namespace std;
State *currentState = &have0;
State* Have0State::process(string input){
    if(input == "quarter"){
        cout << "cool" << endl;
    }
    return &have0;
}
int main(int argc, char** argv) {
    string input;
    //get input
    cin >> input;
    while (input != "exit") {
        currentState = currentState->process(input);
        //get input
        cin >> input;
    }
    return 0;
};

我曾尝试将流程函数定义为Have0State::State::process(string input),但也没有成功。任何关于函数指针应该如何工作的澄清,特别是在子类成员函数的上下文中,我都会非常感激

EDIT:另外,state.h文件中Have0State类声明末尾的have0声明究竟是什么?它没有明确声明的类型;这是否意味着它属于Have0State类型??

您的示例中没有任何函数指针。此外,像Marciej一样,我能够编译(并运行(这些代码。

但是,由于您提出了要求,"have0"声明只是声明了该类的一个实例。类定义后面可以有0个或多个这样的声明(以及初始化程序(:

class Thing {...} one, another, many[3] = { Thing(1), Thing(2), Thing(3) };

与任何其他类型相同:

int counter = 0, flag = 0x80, limit = 500;

这个可选声明符列表的可能性就是为什么类、结构、联合和枚举定义后面必须跟一个分号(以终止列表(。

但是,正如Karthik所说,如果标头包含在多个.cpp文件中,那么在标头中定义变量将在链接时导致"重复定义"错误。IMO使用这种技术在.cpp文件(而不是.h文件(中定义和声明私有对象是可以的。