我在學習函數指針的概念。我寫了一個代碼,這是拋出錯誤,我無法破譯。請看看功能指針編譯時出錯
# 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;
}
在編寫這個程序,我得到線25,27,29以下錯誤:
cannot convert `int (A::*)(int, int)' to `int (*)(int, int)' in return
我也得到錯誤的線43和44是
expected primary-expression before='token'
提示:與交易時函數指針,創建你的'typedef',然後使用它。 – 2012-02-19 14:01:00
聲明我的typedef爲typedef int(A :: * pt2Func)(int,int);刪除了很少的錯誤,但我仍然留下如下錯誤:-'ISO C++禁止採用非限定或帶括號的非靜態成員函數的地址來形成指向成員函數的指針。說'&A :: sum'' – Invictus 2012-02-19 14:04:40