2016-11-08 7 views
0

私はC++を新しくしました.2つのクラスを含むpgmを作成しようとしています。そのうちの1つのクラスは、関数ポインタを介して別のクラスのコールバック関数を生成するメンバ関数を持っていますが、エラー。は、代入pt2function =&B :: generate_callback;で 'int(B :: *)(std :: string)'を 'int(*)(std :: string)'に変換できません。

#include <iostream> 
    #include <string> 

    using namespace std; 



    class B 
    { 
    private: std::string str1; 
    public: int generate_callback(std::string str1); 


    }; 
    int B::generate_callback(std::string str1) 
    { 
     if ((str1=="Generate")||(str1=="generate")) 
     { 
      Cout<<"Callback generated "; 
     } 
    return 0; 
    } 

    class A : public B 
    { 
    public: 
       void count(int a,int b); 
     private: int a,b; 

    }; 


    void A::count(int a, int b) 
    { 
     for (a=1;a<b;a++){ 
      if(a==50) 
      { 
       cout<<"Generating callback "; 

       goto exit; 

     } 
    exit: ; 
    } 
    } 

    int (*pt2function)(string)=NULL; 
    int main() 
    { 
     B obj1; 
     A obj2; 
     string str; 
     cout<<"To generate callback at int i=50 please enter 'generate'"; 
     cin>>str; 
     obj2.count(1,100); 
     pt2function=&B::generate_callback; 
     (obj1.*pt2function)(str); 
     return 0; 
    } 

エラー:

main.cpp:57: error: cannot convert 'int (B::*)(std::string) {aka int (B::*)(std::basic_string<char>)}' to 'int (*)(std::string) {aka int (*)(std::basic_string<char>)}' in assignment 
    pt2function=&B::generate_callback; 

/home/adt/practice/N_practise/n_pract_2/pract2/main.cpp:58: error: 'pt2function' cannot be used as a member pointer, since it is of type 'int (*)(std::string) {aka int (*)(std::basic_string<char>)}' 
    (obj1.*pt2function)(str); 
     ^
     ^
+0

メンバ関数へのポインタは非メンバ関数へのポインタと同じではなく、 'pt2function'は非メンバ関数へのポインタです。私はあなたが['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)と[' std :: bind'](http:// en。代わりにcppreference.com/w/cpp/utility/functional/bind)。 –

+0

@Someprogrammerdude私は関数ポインタを使用する必要がある場合、私は先に進んでいますか? – TheNVP

+0

'pt2function'を' B'メンバ関数へのポインタにする必要があります。構文は、基本的にエラーメッセージに表示されます。 –

答えて

0

変数pt2function非メンバ関数へのポインタです。そのようなポインタは、メンバ関数へのポインタと互換性がありません。コンパイラが最初のエラーであなたに伝えているのは、int (*)(string)int (B::*)(string)と互換性がありません。

あなたはBメンバ関数へのポインタとしてpt2functionを定義する必要があります。

int (B::*pt2function)(string)=NULL; 

今、あなたは変数pt2functionBの整合部材の機能を初期化するか、割り当てることができます。

これはまた、現在のコードでは、変数pt2functionがメンバー関数へのポインタではないため、そのように使用することはできないという第2のエラーを解決します。

0

関数へのポインターとメンバー関数へのポインターは、実際には異なる獣です。

  • 変更この行:これに

    int (*pt2function)(string)=NULL; 
    

    int (B::*pt2function)(string)=NULL; 
    

    としてpt2functionを定義している

    は、あなたはそれがあなたのコードで働いてもらうために、主に2つのオプションがありますBのメンバー関数へのポインタは、を取得します。を返し、intを返します。

  • main機能では、generate_callbackを静的メソッドとして宣言し、と呼びます。
    実際、静的メンバー関数は、すでに使用しているポインタのように機能するポインタに割り当てることができます。

関連する問題