使用指向成员函数的指针的问题
issue with using pointer to member function
这行代码给我带来了很多麻烦:
while(!list.add(list.*get().children()));
它断章取义,但我只是想使用 class 成员函数指针 get()。有人可以提供建设性的反馈吗?
struct State
{
State *children();
};
class List
{
State *getBFS();
State *getDFS();
State *getUCS();
State *getGS();
State *getAStar();
public:
State *(List::*get)();
bool add(State *state);
List(short type)
{
switch(type)
{
case 0: get = &List::getBFS;
break;
case 1: get = &List::getDFS;
break;
case 2: get = &List::getUCS;
break;
case 3: get = &List::getGS;
break;
default: get = &List::getAStar;
}
}
};
int main()
{
List list(0);
while(!list.add((list.*get()).children()));
}
注意是precedence of operator()
is higher than operator.*
,所以你应该改成
list.*get()
到
(list.*get)()
编辑
你想要的应该是
while(!list.add(((list.* list.get)())->children()));
// ~~~~~ ~~
注(1)get
是List
的成员; (2) get
的return类型是指针(即State*
),所以应该使用->
而不是.
。
这行代码给我带来了很多麻烦:
while(!list.add(list.*get().children()));
它断章取义,但我只是想使用 class 成员函数指针 get()。有人可以提供建设性的反馈吗?
struct State
{
State *children();
};
class List
{
State *getBFS();
State *getDFS();
State *getUCS();
State *getGS();
State *getAStar();
public:
State *(List::*get)();
bool add(State *state);
List(short type)
{
switch(type)
{
case 0: get = &List::getBFS;
break;
case 1: get = &List::getDFS;
break;
case 2: get = &List::getUCS;
break;
case 3: get = &List::getGS;
break;
default: get = &List::getAStar;
}
}
};
int main()
{
List list(0);
while(!list.add((list.*get()).children()));
}
注意是precedence of operator()
is higher than operator.*
,所以你应该改成
list.*get()
到
(list.*get)()
编辑
你想要的应该是
while(!list.add(((list.* list.get)())->children()));
// ~~~~~ ~~
注(1)get
是List
的成员; (2) get
的return类型是指针(即State*
),所以应该使用->
而不是.
。