c++での関数ポインタ
c++の関数ポインタ(メンバ関数ポインタ)についてちょっと練習. ポインタ型を宣言する時,クラスまで指定するのでCの関数ポインタよりも安全だそう.
以下のソース(func_pointer.hpp, func_pointer.cpp)は関数ポインタの旨みみたいのを活かしてるとは言えないと思うんだけど,とりあえず今やりたいことを実現するにはこれで十分かな?
ヘッダ:func_pointer.hpp
namespace FP {
class Func_pointer
{
private:
int add( int a, int b ); /// 加算を行うメソッド
int sub( int a, int b ); /// 減算を行うメソッド
int multi( int a, int b ); /// 乗算を行うメソッド
int (Func_pointer::*func_ptr)( int a, int b ); /// 関数ポインタfunc_ptrの宣言.関数ポインタ自体はprivateとする
public:
enum METHOD { ADD=0, SUB, MULTI };
Func_pointer() { func_ptr = &Func_pointer::add; }; /// コンストラクタでは適当に加算メソッドを選択しておく
void select_func( Func_pointer::METHOD mode ); /// 計算方法を選択するメソッド
int caluculate( int a, int b ); /// 計算メソッド
};
}
ソース:func_pointer.cpp
#include <iostream>
#include "func_pointer.hpp"
using namespace FP;
int main( void ) {
Func_pointer test;
int a = 10; int b = 5;
/// 加算
Func_pointer::METHOD mode = Func_pointer::ADD;
test.select_func( mode );
std::cout << "The answer is " << test.caluculate( a, b ) << "." << std::endl;
/// 減算
mode = Func_pointer::SUB;
test.select_func( mode );
std::cout << "The answer is " << test.caluculate( a, b ) << "." << std::endl;
/// 乗算
mode = Func_pointer::MULTI;
test.select_func( mode );
std::cout << "The answer is " << test.caluculate( a, b ) << "." << std::endl;
return 0;
}
int Func_pointer::add( int a, int b ) {
return a+b;
}
int Func_pointer::sub( int a, int b ) {
return a-b;
}
int Func_pointer::multi( int a, int b ) {
return a*b;
}
void Func_pointer::select_func( Func_pointer::METHOD mode ) {
switch ( mode ) {
case Func_pointer::ADD:
func_ptr = &Func_pointer::add;
break;
case Func_pointer::SUB:
func_ptr = &Func_pointer::sub;
break;
case Func_pointer::MULTI:
func_ptr = &Func_pointer::multi;
break;
default:
std::cout << "Illegal mode selection." << std::endl;
exit(0);
}
}
int Func_pointer::caluculate( int a, int b ) {
return (this->*func_ptr)( a, b ); /// どのインスタンスの関数ポインタかを指定するため,thisが必要
}
実行結果:
The answer is 15.
The answer is 5.
The answer is 50.
うん,うまくいってますね.今日はイライラせずに済んだ.
以下のページを参考にさせていただきました.