以前在C裡面function pointer不失是一種很神祕而且很好用的工具,

而到了C++的class method的時候,卻因為overloaded-function造成這個特性的喪失,

其實也不是沒有解法的,

C的function pointer:

typedef void (*FunctionType)(int, int);

void sum(int a, int b) {

int c = a + b;

}

FunctionType fn = sum;

// calling

fn();

 


C++的class method pointer:

class MyClass {

public:

MyClass(int a) : mA(a) {}


...

void sum(int a, int b);

return a + b + mA;

};

...

protected:

int mA;

}

 

// Method is a function pointer whose type is (MyClass::*)(int, int),

// its name can be customized by you.

void (MyClass::*Method)(int, int) = &(MyClass::sum);

 

// calling

MyClass obj(1), o2(10);

// obj is a instance of MyClass, and the Method is just a function pointer.

int result = (obj.*)Method(2, 3);

// result is 6.

result = (o2.*)Method(9, 8);

// result is 27.

看起來很麻煩,搭配template用起來可是威力十足呢~

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 jimmy899 的頭像
    jimmy899

    荒廢的記事本

    jimmy899 發表在 痞客邦 留言(0) 人氣()