2013-02-16 21 views
0

我在使用函數指針實現有限狀態機時遇到了問題。我不斷收到錯誤:有限狀態機中的函數指針

b.cpp: In function ‘int main()’: 
b.cpp:51: error: ‘have0’ was not declared in this scope 

我試圖在第51行添加&到對此商品有0,但沒有做任何事情。我一直在閱讀函數指針一個小時,但仍然無法編譯它。我覺得我對函數指針的理解非常好,但很顯然,我在這裏錯過了一些東西。我所有的功能都是空白的,因爲我只是想立即編譯它們,它們最終將充滿邏輯來移動通過有限狀態機。任何幫助表示讚賞。這裏是我的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; 


} 

和我的BH:

#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

我在'b.cpp'中看不到'have0'的聲明。我同意編譯器。 – 2013-02-16 06:22:22

+0

我沒有原型聲明'void have0(std :: string);'? – midma101 2013-02-16 06:24:48

+0

是的,但我認爲你需要方法體聲明。原型沒有*地址*。 – 2013-02-16 06:26:00

回答

1

have0have25,等等,您已經定義的所有成員函數,所以要得到他們的地址,需要類似於:&b::have0。但是請注意,你不能將它分配給一個指向函數的指針 - 它是一個指向成員函數的指針,這在某些方面大致類似,但絕對不是一回事(也不能替代另一個)。

換句話說,您當前使用的state的定義將無法保存指向成員函數的指針。同樣,試圖使用statemain中的代碼對於指向成員函數的指針也不起作用。

最明顯的(也許最好的,至少基於我們目前看到的)處理這個問題的方法是將b從一個類更改爲一個名稱空間。你似乎沒有打算創建b的實例,所以它看起來像一個名稱空間可能更適合你的需求。

2

您已將have0作爲b類的成員函數,因此您不能僅指向它「獨立」;它只存在於類的一個實例中(然後簽名將不會與你的函數指針的簽名相匹配,因爲將有引用傳遞給對象本身的隱藏參數)。

最簡單的解決方法是刪除類b完全,特別是因爲你似乎並沒有被目前使用它的任何東西,即頭將只是:沒有

#include <string> 

void have0(std::string); 
… 

和函數的定義前綴爲b::