指向成员函数的指针 - 不想工作

时间:2012-03-31 10:09:59

标签: c++ pointers

在这个简短的代码中:

class X
{
private:
    class Y
    {

    public:
        typedef void (X::* ptr_to_mem)();
        Y(X* parent,ptr_to_mem ptr):parent_(parent),ptr_(ptr)
        {}
        void run()
        {
            parent_->*ptr_();//at this line I'm getting an error
        }
    private:
        X* parent_;
        ptr_to_mem ptr_;
    };

public:
    void some_fnc()
    {
        cout << "some_fnc";
    }

    void another()
    {
        Y y_(this,&X::some_fnc);
        y_.run();
    }

};

错误:

error: must use '.*' or '->*' to call pointer-to-member function in '((X::Y*)this)->X::Y::ptr_ (...)', e.g. '(... ->* ((X::Y*)this)->X::Y::ptr_) (...)'

1 个答案:

答案 0 :(得分:6)

添加一对额外的parens:

(parent_->*ptr_)();

请参阅C++FAQ lite 33.6