我在使用函数指针实现有限状态机时遇到了麻烦。我一直收到错误:
b.cpp: In function ‘int main()’:
b.cpp:51: error: ‘have0’ was not declared in this scope
我尝试添加&到第51行的have0,但没有做任何事情。我已经阅读了一个小时的函数指针,我仍然无法编译它。我觉得我对函数指针的理解非常好,但显然我在这里缺少一些东西。我的所有函数都是空白的,因为我只是想让它立即编译,它们最终会充满逻辑以通过有限状态机。任何帮助表示赞赏。这是我的b.cpp代码:
#include <iostream>
#include <string>
#include "b.h"
using namespace std;
typedef void (*state)(string);
state current_state;
void b::have0(string input)
{
if(input == "quarter"){
}
}
void b::have25(string input)
{
}
void b::have50(string input)
{
}
void b::have75(string input)
{
}
void b::have100(string input)
{
}
void b::have125(string input)
{
}
void b::have150(string input)
{
}
void b::owe50(string input)
{
}
void b::owe25(string input)
{
}
int main()
{
string inputString;
// Initial state.
cout <<"Deposit Coin: ";
cin >> inputString;
cout << "You put in a "+inputString+"." << endl;
current_state = have0;
// Receive event, dispatch it, repeat
while(1)
{
if(inputString == "exit")
{
exit(0);
}
// Pass input to function using Global Function Pointer
(*current_state)(inputString);
cout <<"Deposit Coin: ";
cin >> inputString;
cout << "You put in a "+inputString+"." << endl;
}
return 0;
}
和我的b.h:
#ifndef B_H
#define B_H
#include <string>
class b{
public:
void have0(std::string);
void have25(std::string);
void have50(std::string);
void have75(std::string);
void have100(std::string);
void have125(std::string);
void have150(std::string);
void have175(std::string);
void have200(std::string);
void have225(std::string);
void owe125(std::string);
void owe100(std::string);
void owe75(std::string);
void owe50(std::string);
void owe25(std::string);
};
#endif
答案 0 :(得分:2)
您已将have0
作为班级b
的成员函数,因此您不能仅仅将其指向“独立”;它只存在于类的一个实例中(然后签名不会与你的函数指针匹配,因为会有一个隐藏的参数来传递对象本身的引用)。
最简单的解决方法是完全删除课程b
,特别是因为您似乎没有将它用于当前的任何内容,即标题只是:
#include <string>
void have0(std::string);
…
没有b::
前缀的函数定义。
答案 1 :(得分:1)
您定义的have0
,have25
等都是成员函数,因此要获取其地址,您需要:&b::have0
。但是请注意,你不能将它指定给一个函数的指针 - 它是一个成员函数的指针,在某些方面大致类似,但绝对不是同一个东西(也不能替代另一个) )。
换句话说,您当前使用的state
定义无法保存指向成员函数的指针。同样,试图使用main
的{{1}}中的代码也无法用于指向成员函数的指针。
最明显的(也许是最好的,至少基于我们目前所见到的)处理此问题的方法是将state
从类更改为命名空间。您似乎还没有计划创建b
的实例,因此看起来命名空间可能更符合您的需求。