0

関数ポインターを使用して有限状態マシンを実装するのに問題があります。エラーが発生し続けます:

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

51 行目の have0 に & を追加しようとしましたが、何もしませんでした。関数ポインターについて 1 時間読んでいますが、まだコンパイルできません。関数ポインターの理解はかなり進んでいると思いますが、ここに欠けているものがあることは明らかです。今コンパイルしようとしているだけなので、すべての関数は空白です。最終的には、有限状態マシンを移動するロジックで満たされます。どんな助けでも大歓迎です。ここに私の 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
4

2 に答える 2

2

have0class のメンバー関数を作成したbため、それを単に「スタンドアロン」で指すことはできません。クラスのインスタンスに関連してのみ存在します(オブジェクト自体への参照を渡すための隠し引数があるため、署名は関数ポインターの署名と一致しません)。

最も簡単な修正は、クラスbを完全に削除することです。特に、現在は何も使用していないようです。つまり、ヘッダーは次のようになります。

#include <string>

void have0(std::string);
…

そして、b::接頭辞なしの関数定義。

于 2013-02-16T06:26:27.847 に答える
1

定義したhave0have25などはすべてメンバー関数であるため、それらのアドレスを取得するには、次のようなものが必要です&b::have0。ただし、それを関数へのポインターに割り当てることはできないことに注意してください。これはメンバー関数へのポインターであり、いくつかの点でほぼ類似していますが、間違いなく同じではありません (また、他のものを置き換えることもできません)。 )。

つまり、現在使用している定義はstate、メンバー関数へのポインターを保持するためには機能しません。同様に、main使用しようとするコードはstate、メンバー関数へのポインターに対しては機能しません。

これに対処するための最も明白な (そして少なくともこれまでに見たものに基づくと、おそらく最善の) 方法はb、クラスから名前空間に変更することです。とにかくのインスタンスを作成する予定はないようですbので、おそらく名前空間の方がニーズに合っているようです。

于 2013-02-16T06:25:44.273 に答える