2013-04-29 196 views
11

我想通過成員函數指針調用成員函數。調用函數也是一個成員。如何通過成員函數指針調用成員函數?

class A; 

typedef int (A::*memFun)(); 

class A 
{ 
    int P(){return 1;} 
    int Q(){return 2;} 
    int R(){return 3;} 

    int Z(memFun f1, memFun f2) 
    { 
     return f1() + f2(); //HERE 
    } 
public: 
    int run(); 
}; 

int A::run() 
{ 
    return Z(P, Q); 
} 

int main() 
{ 
    A a; 
    cout << a.run() << endl; 
} 

我沒有做正確,和我越來越無差錯

main.cpp:15:19: error: must use '.*' or '->*' to call pointer-to-member function in 'f1 (...)', e.g. '(... ->* f1) (...)' 
     return f1() + f2(); //HERE 

請出示正確的方式去做。

編輯 - 還有另外一個錯誤,這是其具有

return Z(&A::P, &A::Q); 

回答

19
(this->*f1)() + (this->*f2)(); 

Regar無論您是從課堂內部調用它,都必須明確指定要調用的對象(在此例中爲this)。還請注意需要括號。下面是錯誤的:

this->*f1() + this->*f2() 
+0

+1謝謝,這是有效的。在看到編譯器錯誤之後,我確實嘗試了'this - > * f1()+ this - > * f2()',但是它沒有工作。 – 2013-04-29 10:43:58

4

解決像這樣:

(this->*f1)() + (this->*f2)() 
+0

謝謝!那解決了它。但是我有另一個錯誤,我沒有提到,但@Joachim回答了它。 – 2013-04-29 10:40:55

2

,你必須使用這個

(this->*f1)(); 
3

雖然你沒有表現出來,你叫Z時,以及最有可能有錯誤。

你需要調用這樣的功能:

Z(&A::P, &A::Q) 
+0

+1謝謝,解決我剛纔要問的問題。 – 2013-04-29 10:42:08