いろいろなテクニック.Nucleo と DISCO-F746 用.
Dependencies: Array_Matrix mbed
Diff: FunctionPointerInClass.hpp
- Revision:
- 0:bb939e0bc6e2
diff -r 000000000000 -r bb939e0bc6e2 FunctionPointerInClass.hpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FunctionPointerInClass.hpp Sun Oct 15 11:41:48 2017 +0000 @@ -0,0 +1,33 @@ +//------------------------------------------------ +// クラス内で関数ポインタを使う +// 2016/07/22, Copyright (c) 2016 MIKAMI, Naoki +//------------------------------------------------ + +class MyClass +{ +public: + MyClass(int k) // 実行する処理を,コンストラクタの引数 k で変える + { + if (k==0) fp = &MyClass::GetA; // 関数ポインタに GetA() を割り当てる + else fp = &MyClass::GetB; // 関数ポインタに GetB() を割り当てる + } + void Exec(int &x) { (this->*fp)(x); } +private: + void (MyClass::*fp)(int&); // 関数ポインタ + + // 以下の関数を関数ポインタに割り当てる + void GetA(int& a) { a = 2; } + void GetB(int& a) { a = 5; } +}; + +void MyFunctionPointerClass() +{ + MyClass objA(0); + MyClass objB(1); + + int x; + objA.Exec(x); // GetA() が実行される + printf("a = %d\r\n", x); + objB.Exec(x); // GetB() が実行される + printf("a = %d\r\n", x); +}