您的位置:首页 > 其它

基类成员函数指针使用

2010-12-30 17:03 204 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: