“操作符不匹配 - > * pos - > * op”

问题描述:

编译下面的代码时出现以下错误。我很困惑,无法弄清楚这里有什么问题。成员函数指针解除引用是否错误?“操作符不匹配 - > * 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); 
} 
} 

而不是做这个的:

(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

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

pos.operator->()->*op 

或者干脆

(*pos).*op