最近在用C++Builder时,想要将对象1的成员函数指针赋给对象2的成员变量,然后在对象2内通过该成员变量访问对象1的成员函数。貌似标准的C++不支持这样的操作,但是C++Builder提供了__closure关键字,感觉还挺好用的,测试代码如下:
// Unit1.h
//---------------------------------------------------------------------------
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();
};
// Unit1.cpp
//---------------------------------------------------------------------------
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));
}
// main.cpp
//---------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[]) {
Test1 *test = new Test1(1);
test->Test11();
delete test;
getchar();
return 0;
}
A few years ago I’d have to pay soomene for this information.