简体   繁体   中英

State Machines, Sub-Classes, and Function Pointers

I'm having trouble implementing a state machine for class. I keep getting the errors:

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

I'm trying to get the Have0State to work before I continue onto the rest of the machine, hence the sparse code.

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;
};

I've tried defining the process function as Have0State::State::process(string input) but that didn't work either. Any clarification on how function pointers are supposed to work, especially in the context of subclass member functions, I would greatly appreciate it.

EDIT: Also, what exactly is the have0 declaration at the end of the Have0State class declaration in the state.h file? It doesn't have an explicitly stated type; is it implied that it is of type Have0State??

There aren't any function pointers in your example. Also, like Marciej, I am able to compile (and run) this code.

But, since you asked, the 'have0' declaration simply declares an instance of the class. A class definition can be followed by 0 or more of these declarations (as well as initializers):

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

the same as for any other type:

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

The possibility of this optional declarator list is why class, struct, union, and enum definitions must be followed with a semi-colon (to terminate the list).

But, as Karthik said, defining a variable in a header will cause "duplicate definition" errors at link time, if the header is included in more than one .cpp file. IMO it's fine though to use this technique to define and declare private objects in a .cpp file (rather than a .h file).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM