#include <iostream>#include <vector>// 1.对全局函数指针数组typedeftypedef void(*FuncType01)();typedef FuncType01 Func01Array[2];void foo() { std::cout << "void foo()" << std::endl;}void bar(){ std::cout << "void bar()" << std::endl;}class A {public: // 2.在类中对成员函数指针数组typedef typedef void (A::*FuncType02)() const; typedef FuncType02 Func02Array[2]; void foo() const { std::cout << "void foo() const" << std::endl; } void bar() const { std::cout << "void bar() const" << std::endl; } void test() const { // 调用2的,类内部类型前不需要加类的域 FuncType02 f = &A::foo;// 取成员函数地址必须加&,无论是否在类的内部还是外部 Func02Array fs = {&A::foo, &A::bar}; (this->*f)(); for (int i = 0; i < 2; i++) { (this->*fs[i])(); } }};// 3.在类外对成员函数指针数组typedeftypedef void (A::*FuncType03)() const;typedef FuncType03 Func03Array[2];int main(){ // 调用1的 FuncType01 f1 = ::foo;//&可以不加 Func01Array fs1 = { &foo, &bar }; (*f1)(); for (int i = 0; i < 2; i++) { (*fs1[i])(); } // 调用2的 A::FuncType02 f2 = &A::foo;// 取成员函数地址必须加& A::Func02Array fs2 = {&A::foo, &A::bar}; A a; (a.*f2)(); for (int i = 0; i < 2; i++) { (a.*fs2[i])(); } // 调用3的,不需要加类的域 FuncType03 f3 = &A::foo; Func03Array fs3 = {&A::foo, &A::bar}; A a2; (a2.*f3)(); for (int i = 0; i < 2; i++) { (a2.*fs3[i])(); } a.test(); return 0;}
新闻热点
疑难解答