"no match for operator->* in pos ->* op"

"no match for operator->* in pos ->* op"

本文关键字:gt pos op in no for match operator-      更新时间:2023-10-16

在编译下面的代码时,我得到以下错误。我很困惑,不知道这里出了什么问题。成员函数指针取消引用错误吗?

错误:

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

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

pos.operator->()->*op

(*pos).*op