与ars发布的链接略有不同,您可以将switch语句的值用作函数指针数组中的数组索引。因此,可以这样编写代码:switch (i) { case 0: foo(); break; case 1: bar(); break; case 2: baz(); break; } 你可以做到这一点 typedef void (*func)(); func fpointers[] = {foo, bar, baz}; fpointers[i](); 另外,你可以使用函数指针代替数字,如ars的答案所述。
这里有一个非常好的页面,用C++解释了这个问题: http://oopweb.com/CPP/Documents/FunctionPointers/Volume/CCPP/FPT/em_fpt.html 编辑: 以上链接在2020年6月已失效。可以在此处找到缓存版本: https://web.archive.org/web/20170606042951/http://oopweb.com/CPP/Documents/FunctionPointers/Volume/CCPP/FPT/em_fpt.html