基类成员函数指针使用

 #include <iostream>
#include <string>
#include <functional>

using namespace std;

class Test
{
    public:
        Test()
        {
        }
        Test(const string& str)
            :s(str)
        {

        }

    public:
        int output()
        {
            cout<<s<<endl;
            return 0;
        }
    private:
        string s;
};

template <typename T, typename R>
class my_men_func_t
:public unary_function<T, R>
{
    private:
        R (T::*pmf) ();//声明以T为基类的成员函数指针,并返回类型为R
    public:
        explicit my_men_func_t(R(T::*p)())//需要显示构造以p为函数指针对象。
            :pmf(p)
        {
        }
    public:
        R print(T& X)//成员函数
        {
            return ((X.*pmf)());//调用基类的成员函数
        }
};

int main(int argc, char **argv)
{
    my_men_func_t<Test, int> m(&Test::output);//以基类的函数地址为参数来定义一个对象
    Test t("123");
    m.print(t);//调用成员函数
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chenxijie1985/article/details/6107608
今日推荐