我是c ++新手! 请帮我实施国家模式。
我有下面的代码,但它没有编译:
class MasterThreadState;
class Init; class Idle;
class MasterThread
{
public:
MasterThread(){
_state = Init::State();
}
void handle(int sender, int tag);
private:
int _sender;
MasterThreadState* _state;
private:
friend class MasterThreadState;
void goTo(MasterThreadState* newState){ _state = newState; }
};
class MasterThreadState
{
public:
virtual void recieved(MasterThread& master, int tag);
protected:
void goTo(MasterThread& m, MasterThreadState* newState){
m.goTo(newState);
}
};
class Init : MasterThreadState {
public:
static MasterThreadState& State() { return instance; }
virtual void recieved(MasterThread& master, int tag);
private:
static Init instance;
};
class Idle : MasterThreadState {
public:
void recieved(MasterThread& master,int tag);
static MasterThreadState& State(){ return instance; }
private:
static Idle instance;
};
错误是:
在嵌套名称说明符中使用的不完整类型“Init” _state = Init :: State();
答案 0 :(得分:0)
虚拟功能尚未实施
此代码工作正常:
class MasterThreadState;
class Init; //class Idle;
class MasterThread
{
public:
MasterThread();
void handle(int sender, int tag);
private:
int _sender;
MasterThreadState* _state;
private:
friend class MasterThreadState;
void goTo(MasterThreadState* newState){ _state = newState; }
};
class MasterThreadState
{
public:
virtual void recieved(MasterThread& master, int tag) = 0;
protected:
void goTo(MasterThread& m, MasterThreadState* newState){
m.goTo(newState);
}
};
class Init : MasterThreadState {
public:
static MasterThreadState* State();
virtual void recieved(MasterThread& master, int tag);
private:
Init(){}
};
class Idle : MasterThreadState {
public:
static MasterThreadState* State();
virtual void recieved(MasterThread& master,int tag);
private:
static Idle instance;
};
答案 1 :(得分:0)
如果在Init声明之后移动MasterThread构造函数,代码将编译(和,build):
class MasterThread
{
public:
MasterThread();
void handle(int sender, int tag);
private:
int _sender;
MasterThreadState* _state;
private:
friend class MasterThreadState;
void goTo(MasterThreadState* newState){ _state = newState; }
};
class MasterThreadState
{
public:
virtual void recieved(MasterThread& master, int tag) {}
protected:
void goTo(MasterThread& m, MasterThreadState* newState){
m.goTo(newState);
}
};
class Init : MasterThreadState {
public:
static MasterThreadState* State() { return &instance; }
virtual void recieved(MasterThread& master, int tag) {}
private:
static Init instance;
};
Init Init::instance;
MasterThread::MasterThread() {
_state = Init::State();
}
注意,Init :: State()应返回指针MasterThreadState*
。这也被改变了,静态成员Init :: instance定义,虚拟函数的实现(空)被添加到链接中。