无法在赋值 pt2function=&B::generate_callback 中将 'int (B::*)(std::string)' 转换为 'int (*)(std::string) ';

cannot convert 'int (B::*)(std::string)' to 'int (*)(std::string) ' in assignment pt2function=&B::generate_callback;

我是 c++ 的新手。我正在尝试创建一个包含 2 个 classes 的 pgm,其中一个 class 有一个成员函数,可以在另一个中生成回调函数class 虽然是函数指针,但我不断收到以下错误。

#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);
           ^
           ^

变量pt2function是指向非成员函数的指针。这样的指针与指向成员函数的指针不兼容。这是编译器告诉您的第一个错误:A int (*)(string) is not compatible with a int (B::*)(string).

您需要将 pt2function 定义为指向 B 成员函数的指针:

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

现在您可以将 B 的匹配成员函数初始化或分配给变量 pt2function

这也解决了第二个错误,它基本上是说在您当前的代码中变量 pt2function 不是指向成员函数的指针,因此不能这样使用。

指向函数的指针和指向成员函数的指针真是两回事。

你主要有两种选择让它在你的代码中工作:

  • 更改此行:

    int (*pt2function)(string)=NULL;
    

    为此:

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

    这就是将 pt2function 定义为指向 B 的成员函数的指针,它获得 string 和 returns 的 int.

  • generate_callback 声明为静态方法并在 main 函数中将其作为 pt2function(str); 调用。
    事实上,静态成员函数可以分配给指向函数的指针,就像您已经在使用的函数一样。