deleyd
asked on
C++ linker unresolved symbols (splitting into *.h and *.cpp files)
This sample program worked fine when it was all in one file. when I tried to split it into *.h and *.cpp files I'm getting linker errors now.
Error 1 error LNK2001: unresolved external symbol "public: virtual void __thiscall BaseState::eventA(class Machine *)" (?eventA@BaseState@@UAEXPABaseState.hVMachine@@ @Z) C:\Users\Public\0SBCS\VS\t est\StateP attern3\St atePattern 3\BaseStat e.obj StatePattern3
#pragma once
class Machine; //forward declaration
class BaseState
{
public:
BaseState(void);
public:
virtual void eventA(Machine *m);
virtual void eventB(Machine *m);
};
BaseState.cpp
#include "StdAfx.h"
#include <iostream>
#include "BaseState.h"
using namespace std;
BaseState::BaseState(void)
{
}
void eventA(Machine *m)
{
cout << "\nEventA - do nothing";
}
void eventB(Machine *m)
{
cout << "\nEventB - do nothing";
}
StateONE.h
#pragma once
#include "BaseState.h"
class Machine;
class StateONE : public BaseState
{
public:
StateONE(void);
void eventB(Machine *m);
};
StateONE.cpp
#include "StdAfx.h"
#include <iostream>
#include "StateONE.h"
#include "Machine.h"
using namespace std;
StateONE::StateONE(void)
{
cout << "\n StateONE-ctor ";
};
void StateONE::eventB(Machine *m)
{
cout << "\n In StateONE, handing eventB, switching to stateTwo";
m->setCurrent(&m->stateTwo);
}
StateTWO.h
#pragma once
#include "BaseState.h"
class Machine; //forward declaration
class StateTWO : public BaseState
{
public:
StateTWO(void);
void eventA(Machine *m);
};
StateTWO.cpp
#include "StdAfx.h"
#include <iostream>
#include "StateTWO.h"
#include "Machine.h"
using namespace std;
StateTWO::StateTWO(void)
{
cout << "\n StateTWO-ctor ";
}
void StateTWO::eventA(Machine *m)
{
cout << "\n In StateTWO, handling eventA. Switching to stateOn";
m->setCurrent(&m->stateOne);
}
Machine.h
#pragma once
#include "BaseState.h"
#include "StateONE.h"
#include "StateTWO.h"
class Machine
{
private:
class BaseState *currentState;
public:
Machine(void);
StateONE stateOne;
StateTWO stateTwo;
void setCurrent(BaseState *s);
void HandleEventA();
void HandleEventB();
};
Machine.cpp
#include "StdAfx.h"
#include <iostream>
#include "Machine.h"
using namespace std;
Machine::Machine(void)
{
cout << "\nMachine Constructor";
currentState = &stateTwo;
}
void Machine::HandleEventA()
{
currentState->eventA(this);
}
void Machine::HandleEventB()
{
currentState->eventB(this);
}
void Machine::setCurrent(BaseState *s)
{
currentState = s;
}
Main
#include "stdafx.h"
#include "Machine.h"
int _tmain(int argc, _TCHAR* argv[])
{
Machine fsm;
fsm.HandleEventB();
fsm.HandleEventA();
fsm.HandleEventB();
return 0;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.