您的位置:首页 > 其它

成员函数指针和其他类型的强制转换,使用一般指针调用成员函数

2007-11-09 12:42 399 查看
成员函数指针和其他类型之间的转换,参见如下示例:


class test




...{


public:




void t()...{};


};




typedef void (test::*pMemFnction)();




int main()




...{


pMemFnction method = &test::t; //成员函数指针定义并初始化




int method_ptr = *(int *)&method; //强制转换


pMemFnction m = *(pMemFnction *)&method_ptr; //强制转换, OK




return 0;


}



转换的作用,一方面可能因为特殊的需求,同时也可以方便调试和检查,例如输出函数地址等。也可以使用转换后的指针调用成员方法,比如:




class test




...{


public:




void t()...{cout<<"This is a test!"<<endl;}


};




typedef void (test::*pMemFnction)();




int main()




...{


pMemFnction method = &test::t; //取成员函数


int *method_ptr = (int *)&method; //强制转换为int *





test t;


(t.**(pMemFnction *)method_ptr)(); //使用 method_ptr 调用其成员方法


return 0;


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐