2012-02-19 209 views
0

我在學習函數指針的概念。我寫了一個代碼,這是拋出錯誤,我無法破譯。請看看功能指針編譯時出錯

 # 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' 
+1

提示:與交易時函數指針,創建你的'typedef',然後使用它。 – 2012-02-19 14:01:00

+1

聲明我的typedef爲typedef int(A :: * pt2Func)(int,int);刪除了很少的錯誤,但我仍然留下如下錯誤:-'ISO C++禁止採用非限定或帶括號的非靜態成員函數的地址來形成指向成員函數的指針。說'&A :: sum'' – Invictus 2012-02-19 14:04:40

回答

2

您需要更換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); 

然後,它會工作,因爲它是爲了工作;)

+0

謝謝你LihO :) – Invictus 2012-02-19 16:17:29

1

功能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 
3

指針功能不一樣pointer to (non-static) member functions

有幾種方法可以解決你的計劃,我將概述他們:

  • 使用無功能或靜態的,而不是成員函數
  • 類型更改爲一個指向成員((A::*)(int, int)
  • 使用std::function/std::bind