Hey everybody,
As of this moment i'm trying to work out how to approach a state design. I've come across Source Makers' site http://sourcemaking.com/design_patterns/state/cpp/1 and am testing out the example. The program works fine when it's all in 1 file, although i had to change some stuff in main, but when i separate the program into headers and .cpp errors would occur. This is what i have at the moment. There's quite a lot of errors but i think it all has to do with the "base class not being defined".
The majority of errors are defined as...error C2504: 'State' : base class undefined
<-- This is inside off.herror C2061: syntax error : identifier 'Machine'
<--off.herror C2504: 'State' : base class undefined
<--on.herror C2061: syntax error : identifier 'Machine'
<--on.h
Machine.h
#ifndef Machine_h
#define Machine_h
#include "State.h"
#include <iostream>
using namespace std;
class Machine
{
class State *current;
public:
Machine();
void setCurrent(State *s)
{
current = s;
}
void on();
void off();
};
#endif
Machine.cpp
#include "Machine.h"
Machine::Machine()
{
current = new OFF();
cout << '\n';
}
void Machine::on()
{
current->on(this);
}
void Machine::off()
{
current->off(this);
}
State.h
#ifndef State_h
#define State_h
#include "Machine.h"
#include "Off.h"
#include "On.h"
#include <iostream>
using namespace std;
class State
{
public:
virtual void on(Machine *m);
virtual void off(Machine *m);
};
#endif // !State.h
State.cpp
#include "State.h"
void on(Machine *m)
{
cout << " already ON\n";
}
void off(Machine *m)
{
cout << " already OFF\n";
}
On.h
#ifndef On_h
#define On_h
#include "State.h"
#include <iostream>
using namespace std;
class ON: public State
{
public:
ON()
{
cout << " ON-ctor ";
};
~ON()
{
cout << " dtor-ON\n";
};
void off(Machine *m);
};
#endif // !On
On.cpp
#include "On.h"
void ON::off(Machine *m)
{
cout << " going from ON to OFF";
m->setCurrent(new OFF());
delete this;
}
Off.h
#ifndef Off_h
#define Off_h
#include "State.h"
#include <iostream>
using namespace std;
class OFF: public State
{
public:
OFF()
{
cout << " OFF-ctor ";
};
~OFF()
{
cout << " dtor-OFF\n";
};
void on(Machine *m);
};
#endif // !Off_h
Off.cpp
#include "Off.h"
void OFF::on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON());
delete this;
}
main.cpp
#include <iostream>
using namespace std;
#include "Machine.h"
int main()
{
Machine fsm;
int num;
void(Machine:: *ptrs[])() =
{
&Machine::off, &Machine::on
};
while (1)
{
cout << "Enter 0/1: ";
cin >> num;
(fsm.*ptrs[num])();
}
}
Any help of course be appreciated.
Update: It seems that i can debug and run the program with no problem (errors still pop up). No underlines appear throughout the program. Maybe it's just visual studio 2012 acting up for some reason or maybe it's the code. Still if you think there's an error for some reason please let me know what you think.