我在为类实现状态机时遇到问题。我不断收到错误:状态机,子类和函数指针
state.cpp:5: error: have0 was not declared in this scope
state.cpp:10: error: redefinition of State* Have0State::process(std::string)
state.h:18: error: virtual State* Have0State::process(std::string) previously defined here
我试图让Have0State工作之前,我继续到机器的其余部分,因此稀疏代码。
state.h:
#ifndef STATE_H
#define STATE_H
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
class State{
public:
State(){};
virtual State* process(std::string input) = 0;
};
class Have0State: public State {
public:
Have0State():State(){};
virtual State* process(std::string input);
}have0;
#endif
state.cpp:
#include "state.h"
using namespace std;
State *currentState = &have0;
State* Have0State::process(string input){
if(input == "quarter"){
cout << "cool" << endl;
}
return &have0;
}
int main(int argc, char** argv) {
string input;
//get input
cin >> input;
while (input != "exit") {
currentState = currentState->process(input);
//get input
cin >> input;
}
return 0;
};
我试着定义过程的功能Have0State::State::process(string input)
但也不能工作。关于函数指针应该如何工作的任何澄清,特别是在子类成员函数的上下文中,我将不胜感激。
编辑:另外,什么是have0
声明Have0State
类声明在state.h文件结束?它没有明确说明的类型;是否暗示它是HaveOState类型?
have0定义似乎与C中有时定义结构变量类似。非常罕见,并且稍后会导致问题(标头中的变量总是会这样做),所以您应该将它移到别处。 – 2013-02-25 02:12:13
在'state.h'的定义末尾是否有'{}'?否则重构'have0',看看它是否有帮助。 – 2013-02-25 02:15:15
您确定您向我们展示了与产生错误的代码完全相同的代码吗?我只是将代码(头文件的内容和头文件下面的cpp文件的内容,忽略了'#ifndef'后卫)粘贴到在线编译器中,并且它编译得很好。 – 2013-02-25 02:17:01