我有一个具有特殊数据结构的类Test
。 甲Test
类的成员是std::map
其中键是一个std::string
和映射的值是定义如下一个struct
:从结构中调用指针到成员函数指向的函数
typedef struct {
void (Test::*f) (void) const;
} pmf_t;
初始化是OK。问题是当我试图调用指向的函数时。我编写了一个玩具的例子来重现这个问题。那就是:
#include <iostream>
#include <map>
using namespace std;
class Test;
typedef void (Test::*F) (void) const;
typedef struct {
F f;
} pmf_t;
class Test
{
public:
Test() {
pmf_t pmf = {
&Test::Func
};
m["key"] = pmf;
}
void Func (void) const {
cout << "test" << endl;
}
void CallFunc (void) {
std::map<std::string, pmf_t>::iterator it = m.begin();
((*it).second.*f)(); // offending line
}
std::map<std::string, pmf_t> m;
};
int main()
{
Test t;
t.CallFunc();
return 0;
}
由于提前, JIR
彻底的解释,谢谢。我从来没有想过在迭代器中加上'this'。 – Jir
你没有把它加入迭代器;你将它加入到指向成员的表达式中。 (' - >'和'.'运算符的绑定比' - > *'更紧密;这里是一个完全括号的版本:'(this - > *((it-> second).f))()'。 –