2013-04-24 677 views
3

編譯下面的代碼時出現以下錯誤。我很困惑,無法弄清楚這裏有什麼問題。成員函數指針解除引用是否錯誤?「操作符不匹配 - > * pos - > * op」

錯誤:

#g++ fp.cpp 
fp.cpp: In member function âvoid Y::callfptr(void (X::*)(int))â: 
fp.cpp:33: error: no match for âoperator->*â in âpos ->* opâ 

fp.cpp

#include <iostream> 
#include <vector> 
using namespace std; 

class B { 
// some base class 
}; 

class X : public B { 
public: 
    int z; 
    void a(int a) { 
    cout << "The value of a is "<< a << endl; 
    } 
    void f(int b) { 
    cout << "The value of b is "<< b << endl; 
    } 
}; 

class Y : public B { 
public: 
    int b; 
    vector<X> vy; 
    void c(void) { 
    cout << "CLASS Y func c called" << endl; 
    } 
    void callfptr(void (X::*op)(int)); 
}; 

void Y::callfptr(void (X::*op) (int)) { 
vector<X>::iterator pos; 
for (pos = vy.begin(); pos != vy.end(); pos++) { 
    (pos->*op) (10); 
} 
} 

回答

4

而不是做這個的:

(pos->*op) (10); 

這樣做:

((*pos).*op)(10); 

迭代器不需要提供operator ->*的超載。如果你真的想使用operator ->*代替operator .*,那麼你可以做:

((pos.operator ->())->*op)(10) 

但這只是更詳細。

可能與您的使用案例有關的差異是運算符->*可能超載,而operator .*不能。

+0

是解決我的問題,並很好的解釋太... – user1663533 2013-04-24 11:30:45

+0

@ user1663533十分感謝:很高興它幫助:) – 2013-04-24 11:31:22

2

->*operator ->*。您可以使用

pos.operator->()->*op 

或者乾脆

(*pos).*op