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

本文详细介绍了如何在C++Builder中使用__closure关键字,将一个对象的成员函数指针赋给另一个对象的成员变量,并通过该变量调用原对象的成员函数。通过实例代码展示了测试类之间的交互过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在用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
//---------------------------------------------------------------------------
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
// 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));
}
01
02
03
04
05
06
07
08
09
// main.cpp
//---------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[]) {
  Test1 *test = new Test1(1);
  test->Test11();
  delete test;
  getchar();
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值