指向函数的指针编译时出错



我正在尝试学习函数指针的概念。我写了一个代码,它抛出了我无法破译的错误。请看一下

     # include<iostream>
     # include<stdio.h>
     # include<conio.h>
     using namespace std;
     typedef int(*pt2Func)(int,int);
     class A
     {
           private : int x;
                     int y;
           public:
                  A(){}
                  A(int a, int b)
                  {
                   x=a;
                   y=b;
                  } 
                  int sum(int a, int b){return a+b;}
                  int sub( int a , int b){return a-b;}
                  int mult( int a, int b){return a*b;}
                  pt2Func GetPtr2(const char c)
                  {
                      if (c == '+')
                      return &sum;    // line 25
                      else if(c== '-')
                      return &sub;    // line 27
                      else if(c=='*')
                      return &mult;   //line 29
                  }
                  void pass_ptr(int (*pointer_fn)(int,int))
                  {
                   int result;
                   result=(*pointer_fn)(10,5);
                   cout << " result is : " << result;
                  }
                   ~A(){}
     };
     int main()
     {
        A a(0,5); 
        pt2Func=(a.GetPtr2)('+');          //line 43
        int result = (a.*pt2Func)(5,10);   //line 44
        cout << "result is " << result;
        getch();
        return 0;  
     }

在编译这个程序时,我在第25、27、29行中得到以下错误:

cannot convert `int (A::*)(int, int)' to `int (*)(int, int)' in return 

我在第43行和第44行也有错误,这是

expected primary-expression before='token'

指向函数的指针与指向(非静态)成员函数的指针不同。

有几种方法可以修复你的程序,我将概述它们:

  • 使用自由函数或静态函数而不是成员函数
  • 将类型更改为指向成员((A::*)(int, int))的指针
  • 使用std::function/std::bind

您需要将typedef int(*pt2Func)(int,int);替换为:

 class A;                                 // <-- forward declaration
 typedef int (A::*pt2Func)(int,int);

然后,您需要将return &sum;替换为return &A::sum;,以便它与您定义的类型相匹配。

您还需要更换这些线路:

pt2Func=(a.GetPtr2)('+');         // <-- pt2Func is type, name of variable is missing
int result = (a.*pt2Func)(5,10);  // <-- type name (pt2Func) is not allowed here

这些:

pt2Func ptr = a.GetPtr2('+');
int result = (a.*ptr)(5, 10);

然后它将按预期工作;)

指向成员函数的指针与指向函数的指针不同。我建议阅读专门讨论这个主题的C++常见问题部分:[33]指向成员函数的指针

函数sum()非静态成员函数,其类型不是int (*)(int,int)。它的类型是int (A::*)(int,int),如编译器错误消息中所示。其他两个函数也是如此:submult

有两种解决方案。简单的解决方案是使这些函数成为static成员函数,然后程序中的所有内容都可以正常工作,除了以下内容:

//pt2Func=(a.GetPtr2)('+'); //line 43 - error
pt2Func=a.GetPtr2('+');     //line 43 - corrected
//int result = (a.*pt2Func)(5,10); //line 44 - error
int result = pt2Func(5,10);        //line 44 - corrected

最新更新