状态机、子类和函数指针
State Machines, Sub-Classes, and Function Pointers
我在实现类的状态机时遇到问题。我不断收到错误:
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)
,但也没有成功。任何关于函数指针应该如何工作的澄清,特别是在子类成员函数的上下文中,我都会非常感激
EDIT:另外,state.h文件中Have0State
类声明末尾的have0
声明究竟是什么?它没有明确声明的类型;这是否意味着它属于Have0State类型??
您的示例中没有任何函数指针。此外,像Marciej一样,我能够编译(并运行(这些代码。
但是,由于您提出了要求,"have0"声明只是声明了该类的一个实例。类定义后面可以有0个或多个这样的声明(以及初始化程序(:
class Thing {...} one, another, many[3] = { Thing(1), Thing(2), Thing(3) };
与任何其他类型相同:
int counter = 0, flag = 0x80, limit = 500;
这个可选声明符列表的可能性就是为什么类、结构、联合和枚举定义后面必须跟一个分号(以终止列表(。
但是,正如Karthik所说,如果标头包含在多个.cpp文件中,那么在标头中定义变量将在链接时导致"重复定义"错误。IMO使用这种技术在.cpp文件(而不是.h文件(中定义和声明私有对象是可以的。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针