函数指针
2016-02-16 00:08
232 查看
(1/2)类型
普通函数指针不能被赋值为成员函数的地址。int (*pFunc)();
pFunc是一个函数指针,而int (*)()是类型。
成员函数地址要赋值给成员函数指针。
class Base { public: int func() { return 1; } }; int main() { int (*pFunc)(); pFunc = &Base::func; //error: cannot convert 'int (Base::*)()' to 'int (*)()' in assignment return 0; }
class Base { public: int func() { return 1; } }; int main() { int (Base::*pFunc)(); // OK pFunc = &Base::func; return 0; }
再来:
class Base { public: int func() { return 1; } }; class Derived : public Base { public: int foo() { return 1; } }; int main() { typedef int (Base::*FuncPtr)(); FuncPtr fPtr = &Derived::foo; // error return 0; }
需进行强制类型转换
......
FuncPtr fPtr = (FuncPtr)&Derived::foo; // OK
反过来,基类成员函数地址可赋值给指向派生类成员函数的指针。
class Base { public: int func() { return 1; } }; class Derived : public Base { public: int foo() { return 1; } }; int main() { typedef int (Derived::*FuncPtr)(); FuncPtr fPtr = &Base::func; // OK return 0; }
(2/2)调用
class Base { public: virtual void func(int i) { cout << "Base: " << i << endl; } }; class Derived : public Base { public: virtual void func(int i) { cout << "Derived: " << i << endl; } }; int main() { typedef void (Base::*FuncPtr)(int); FuncPtr fPtr = &Base::func; Base b; (b.*fPtr)(2); Derived* dPtr = new Derived(); (dPtr->*fPtr)(2); Base* bPtr = new Derived(); (bPtr->*fPtr)(2); return 0; }
output:
Base: 2
Derived: 2
Derived: 2
相关文章推荐
- JSTL
- IOS-网络(ASI使用)
- 1644 免费馅饼 题解(c++)
- 学习笔记5 Supervised Convolutional Neural Network 之 Stochastic Gradient Descent
- 1644 免费馅饼 题解(c++)
- 选择Nvidia显卡还是ATI显卡
- 微信公众号入门笔记(四)velocity生成xml中文转义问题
- 深入解读Python解析XML的几种方式
- bpython 功能强大的Python shell
- 十条建议帮你提高Python编程效率
- 轻松实现python搭建微信公众平台
- python实现红包裂变算法
- Python实现快速排序和插入排序算法及自定义排序的示例
- Redis学习笔记(4) Redis事务、生存时间及排序
- Hard题目总结
- Python的GUI框架PySide的安装配置教程
- 使用PHP处理数据库数据如何将数据返回客户端并显示当前状态
- PHP模拟post提交数据方法汇总
- thinkphp3.2点击刷新生成验证码
- HTML中嵌入PHP的简单方法