回调函数的实现(指向类成员函数的指针)
参考《C和C++代码精粹》——Chunk Allison
菜单实现
#include <iostream> using namespace std; class Object { public: void retrieve() {cout << "Object::retrieve\n";} void insert() {cout << "Object::insert\n";} void update() {cout << "Object::update\n";} void process(int choice); private: static void (Object::*farray[3])(); }; void (Object::*Object::farray[3])()= { &Object::retrieve, &Object::insert, &Object::update }; void Object::process(int choice) { if (0 <= choice && choice <= 2) { (this->*farray[choice])(); } } int main() { int show_menu(void); Object o; for (;;) { int choice = show_menu(); cout << "choice=" << choice << endl; if (1<=choice && choice <= 3) { o.process(choice-1); } else if (choice == 4) { break; } } return 0; } int show_menu(void) { cout << "==================MENU===================" << endl; cout << "1. retrieve" << endl; cout << "2. insert" << endl; cout << "3. update" << endl; cout << "4. exit" << endl; cout << "please input witch number you choose:"; char input; cin>>input; return input-'0'; }
运行效果
使用typedef使指向成员函数的指针更清晰
#include <iostream> using namespace std; class Object { public: void retrieve() {cout << "Object::retrieve\n";} void insert() {cout << "Object::insert\n";} void update() {cout << "Object::update\n";} void process(int choice); private: typedef void (Object::*Omf)(); static Omf farray[3]; // static void (Object::*farray[3])(); }; Object::Omf Object::farray[3] = //void (Object::*Object::farray[3])()= { &Object::retrieve, &Object::insert, &Object::update }; void Object::process(int choice) { if (0 <= choice && choice <= 2) { (this->*farray[choice])(); } } int main() { int show_menu(void); Object o; for (;;) { int choice = show_menu(); cout << "choice=" << choice << endl; if (1<=choice && choice <= 3) { o.process(choice-1); } else if (choice == 4) { break; } } return 0; } int show_menu(void) { cout << "==================MENU===================" << endl; cout << "1. retrieve" << endl; cout << "2. insert" << endl; cout << "3. update" << endl; cout << "4. exit" << endl; cout << "please input witch number you choose:"; char input; cin>>input; return input-'0'; }
作者:涵曦(www.hanxi.cc)
出处:hanxi.cnblogs.com
GitHub:github.com/hanxi
Email:im.hanxi@gmail.com
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
《 Skynet 游戏服务器开发实战》
-
学习地址:
-
优惠推荐码:
2CZ2UA5u
-
可以先免费试学前 2 章内容