最近在用C++Builder时,想要将对象1的成员函数指针赋给对象2的成员变量,然后在对象2内通过该成员变量访问对象1的成员函数。貌似标准的C++不支持这样的操作,但是C++Builder提供了__closure关键字,感觉还挺好用的,测试代码如下:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
class
Test1 {
private :
int
m_Add;
public :
__fastcall Test1( int
Add) {
m_Add = Add;
};
virtual
__fastcall ~Test1() {};
int
__fastcall TestFunction1( int
param1);
void
__fastcall Test11();
};
class
Test2 {
public :
__fastcall Test2() {};
virtual
__fastcall ~Test2() {};
int
__fastcall(__closure *TestFunction2)( int
param1);
void
__fastcall Test22();
};
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
|
int
__fastcall Test1::TestFunction1( int
param1) {
return
param1 + m_Add;
}
void
__fastcall Test1::Test11() {
Test2 *test2 =
new
Test2();
test2->TestFunction2 = &TestFunction1;
test2->Test22();
delete
test2;
};
void
__fastcall Test2::Test22() {
printf ( "Result: %d" ,
TestFunction2(1));
}
|
01
02
03
04
05
06
07
08
09
|
int
_tmain( int
argc, _TCHAR* argv[]) {
Test1 *test =
new
Test1(1);
test->Test11();
delete
test;
getchar ();
return
0;
}
|