您好,我尝试根据为 Java 编写的sourcemaking站点的代码在 C++ 中实现状态模式。
#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;
}
正如您在“风扇”类之前看到的,我已经预定义了状态类。但是编译器给了我一个错误 使用未定义的类型
第二个问题是在sourcemaking网站上有状态模式的C++实现,但它也给了我一个错误,主函数中的代码不清楚。链接在这里。谢谢