C++ 编译时指向函数错误的指针
我试图学习函数指针的概念。我写了一个代码,它抛出了我无法破译的错误。请看一看C++ 编译时指向函数错误的指针,c++,c++11,C++,C++11,我试图学习函数指针的概念。我写了一个代码,它抛出了我无法破译的错误。请看一看 # include<iostream> # include<stdio.h> # include<conio.h> using namespace std; typedef int(*pt2Func)(int,int); class A { private : int x;
# 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 ∑ // line 25
else if(c== '-')
return ⊂ // 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;
}
我在第43行和第44行也得到了错误,它们是
expected primary-expression before='token'
指向成员函数的指针与指向函数的指针不同。我建议阅读C++主题FAQ章节:.< /P> < P>函数<代码> SUME()/<代码>是非静态成员函数,类型不是<代码> int(*)(int,int)< />。它的类型是
int(A::*)(int,int)
,如编译器错误消息所示。其他两个函数也是如此:sub
和mult
有两种解决办法。简单的解决方案是将这些函数设置为静态成员函数,这样程序中的所有内容都可以正常工作,除了以下内容:
//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
指向函数的指针不同于 有几种方法可以修复您的程序,我将概述它们:
- 使用自由函数或静态函数代替成员函数
- 将类型更改为指向成员的指针(
)(a::*)(int,int)
- 使用
/std::function
std::bind
typedef int(*pt2Func)(int,int)代码>带有:
class A; // <-- forward declaration
typedef int (A::*pt2Func)(int,int);
有了这些:
pt2Func ptr = a.GetPtr2('+');
int result = (a.*ptr)(5, 10);
然后它将按预期的方式工作;) 提示:在处理函数指针时,创建您的typedef
,然后使用它。将我的typedef声明为typedef int(A::*pt2Func)(int,int);删除错误,但我仍然有错误:-<代码> ISO C++禁止使用不合格或括号的非静态成员函数的地址,以形成指向成员函数的指针。说
&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);