C++Builder中__closure关键字的用法

来源:互联网 发布:tk的域名 编辑:程序博客网 时间:2024/05/21 10:21

最近在用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
// Unit1.h
//---------------------------------------------------------------------------
classTest1 {
private:
  intm_Add;
 
public:
  __fastcall Test1(intAdd) {
    m_Add = Add;
  };
  virtual__fastcall ~Test1() {};
 
  int__fastcall TestFunction1(intparam1);
  void__fastcall Test11();
};
 
//---------------------------------------------------------------------------
classTest2 {
public:
  __fastcall Test2() {};
  virtual__fastcall ~Test2() {};
 
  int__fastcall(__closure *TestFunction2)(intparam1);
  void__fastcall Test22();
};
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
// Unit1.cpp
//---------------------------------------------------------------------------
int__fastcall Test1::TestFunction1(intparam1) {
  returnparam1 + m_Add;
}
 
//---------------------------------------------------------------------------
void__fastcall Test1::Test11() {
  Test2 *test2 =new Test2();
  test2->TestFunction2 = &TestFunction1;
  test2->Test22();
  deletetest2;
};
 
//---------------------------------------------------------------------------
void__fastcall Test2::Test22() {
  printf("Result: %d", TestFunction2(1));
}
01
02
03
04
05
06
07
08
09
// main.cpp
//---------------------------------------------------------------------------
int_tmain(intargc, _TCHAR* argv[]) {
  Test1 *test =new Test1(1);
  test->Test11();
  deletetest;
  getchar();
  return0;
}

0 0
原创粉丝点击