编译以下代码时出现以下错误。我很困惑,无法弄清楚这里出了什么问题。成员函数指针取消引用错误吗?

错误:

#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â

文件
#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 .* 不能。

关于c++ - "no match for operator->* in pos ->* op",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16189977/

10-11 22:43
查看更多