#include <iostream>#include <vector>// 1.對(duì)全局函數(shù)指針數(shù)組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.在類中對(duì)成員函數(shù)指針數(shù)組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 { // 調(diào)用2的,類內(nèi)部類型前不需要加類的域 FuncType02 f = &A::foo;// 取成員函數(shù)地址必須加&,無(wú)論是否在類的內(nèi)部還是外部 Func02Array fs = {&A::foo, &A::bar}; (this->*f)(); for (int i = 0; i < 2; i++) { (this->*fs[i])(); } }};// 3.在類外對(duì)成員函數(shù)指針數(shù)組typedeftypedef void (A::*FuncType03)() const;typedef FuncType03 Func03Array[2];int main(){ // 調(diào)用1的 FuncType01 f1 = ::foo;//&可以不加 Func01Array fs1 = { &foo, &bar }; (*f1)(); for (int i = 0; i < 2; i++) { (*fs1[i])(); } // 調(diào)用2的 A::FuncType02 f2 = &A::foo;// 取成員函數(shù)地址必須加& A::Func02Array fs2 = {&A::foo, &A::bar}; A a; (a.*f2)(); for (int i = 0; i < 2; i++) { (a.*fs2[i])(); } // 調(diào)用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;}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注