【问题标题】:issue with using pointer to member function使用指向成员函数的指针的问题
【发布时间】:2017-02-07 06:36:15
【问题描述】:

这行代码给我带来了很多麻烦:

while(!list.add(list.*get().children()));

它脱离了上下文,但我只是尝试使用类成员函数指针 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()));
}

【问题讨论】:

    标签: c++ function pointers operator-precedence member-function-pointers


    【解决方案1】:

    注意operator()precedence高于operator.*,所以应该改

    list.*get()
    

    (list.*get)()
    

    编辑

    你想要的应该是

    while(!list.add(((list.* list.get)())->children()));
    //                       ~~~~~       ~~
    

    注(1)getList的成员; (2)get的返回类型是一个指针(即State*),所以你应该使用->而不是.

    【讨论】:

    • 感谢您的建议,我试过了,但仍然显示“标识符“get”未定义”。这里是我声明指针的地方:State *(List::*get)();
    • @tayfun2150 需要更多上下文。最好提供一个可以重现错误的mcve
    • 非常感谢您的解决方案!我不明白为什么它是 (list.*list.get)() 而不是 (list.*get)(),但它似乎有效
    • @tayfun2150 因为get是会员,所以你应该用list.get,就像你写的list.add一样。
    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多