编译以下代码时出现以下错误。我很困惑,我无法弄清楚这里有什么问题。成员函数指针是否引用错误?
错误:
#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);
}
}
答案 0 :(得分:4)
而不是这样做:
(pos->*op) (10);
这样做:
((*pos).*op)(10);
迭代器不需要提供operator ->*
的重载。如果您真的想使用operator ->*
代替operator .*
,那么您可以这样做:
((pos.operator ->())->*op)(10)
但这只是更冗长。
可能与您的用例相关的差异是,运算符->*
可能会过载,而operator .*
则不能。
答案 1 :(得分:2)
->*
是operator ->*
。你可以使用
pos.operator->()->*op
或只是
(*pos).*op