c++中的函式指標和類成員函式指標
阿新 • • 發佈:2019-01-03
// // main.cpp // Demo // // Created by 杜國超 on 16/12/28. // Copyright © 2016年 杜國超. All rights reserved. // #include using namespace std; class MYClass { public: static void staticfunc(); void test(int a,int b); virtual void sing(); virtual void run(); }; void MYClass::staticfunc() { std::cout <<"MYClass staticfunc" << std::endl; } void MYClass::test(int a,int b) { std::cout <<"MYClass test=" << a + b << std::endl; } void MYClass::sing() { std::cout << "MYClass Sing" << std::endl; } void MYClass::run() { std::cout << "MYClass run" << std::endl; } class ChildClass : public MYClass { public: void test (int a,int b); virtual void sing(); }; void ChildClass::test(int a,int b) { std::cout <<"ChildClass test=" << a - b << std::endl; } void ChildClass::sing() { std::cout << "ChildClass Sing" << std::endl; } typedef void (MYClass::* DGUCO_FUNC)(int,int); typedef void (MYClass::* DGUCO_FUNC1)(); typedef void (ChildClass::* DGUCO_FUNC2)(int,int); typedef void (ChildClass::* DGUCO_FUNC3)(); typedef void (* DGUCO_FUNC4)(); int main(int argc, const char * argv[]) { //父類成員函式指標指向父類成員函式 DGUCO_FUNC func1 = &MYClass::test; DGUCO_FUNC1 func2 = &MYClass::sing; //父類成員函式指標指向子類覆蓋父類成員函式(不允許) // DGUCO_FUNC func3 = &ChildClass::test; // DGUCO_FUNC1 func4 = &ChildClass::sing; //子類成員函式指標指向父類和子類成員函式 DGUCO_FUNC2 func5 = &MYClass::test; DGUCO_FUNC2 func6 = &ChildClass::test; //子類成員函式指標指向父類和子類成員函式 DGUCO_FUNC3 func7 = &MYClass::sing; DGUCO_FUNC3 func8 = &ChildClass::sing; //父類成員函式指標指向父類和子類成員函式 DGUCO_FUNC1 func9 = &MYClass::run; DGUCO_FUNC1 func10 = &ChildClass::run; //靜態成員函式 DGUCO_FUNC4 func11 = &MYClass::staticfunc; MYClass Ca; ChildClass Cb; int a = 6; int b = 4; std::cout << "**************************" << std::endl; (Ca.*func1)(a,b); (Cb.*func1)(a,b); std::cout << "**************************" << std::endl; //多型呼叫 (Ca.*func2)(); (Cb.*func2)(); std::cout << "**************************" << std::endl; (Cb.*func5)(a,b); (Cb.*func6)(a,b); std::cout << "**************************" << std::endl; (Cb.*func7)(); (Cb.*func8)(); std::cout << "**************************" << std::endl; (Ca.*func9)(); (Ca.*func10)(); std::cout << "**************************" << std::endl; func11(); }