vendredi 16 juin 2017

State Pattern in C++ with predefined classes [duplicate]

This question already has an answer here:

Hello I tried to implement State pattern in C++ based on code from sourcemaking site that has been written for Java.

#include<iostream>
#include<conio.h>

using namespace std;
class State {
public:
    virtual void pull(class Fan* f) = 0;
};

class Off;
class Medium;
class High;

class Fan {
private:
    State* current_state;
public:
    void set_state(State* s) {
        current_state = s;
    }
    Fan() {
        current_state = new Off();
    }
    void pull() {
        current_state->pull(this);
    }

};

class Off:public State{
public:
    void pull(Fan *f){
        f->set_state(new Medium());
        cout << "Medium speed" << endl;
    }
};
class Medium:public State {
public:
    void pull(Fan* f) {
        f->set_state(new High());
        cout << "Max speed" << endl;
    }
};
class High :public State {
public:
    void pull(Fan *f) {
        f->set_state(new Off());
        cout << "The fan is off" << endl;
    }
};

int main() {

    Fan* fan = new Fan();
    int c;
    while (1)
    {
        cin>>c;
        fan->pull();
    }

    return 0;
}

As you see before the "Fan" class I have predefined state classes. But compiler gives me an errors use undefined types

The second question is that on sourcemaking site there is C++ implementation of the state pattern, but it also gives me an error and the code in the main function is unclear. The link is here. Thank you

Aucun commentaire:

Enregistrer un commentaire