类函数指针

 

#include < iostream >
using   namespace  std;

class  Test
{
public:
 typedef 
void (Test::*Fun)(int);

 
void test1(int a)
 
{
  cout
<<"this is test1"<<endl;
 }

 
void test2(int a)
 
{
  cout
<<"this is test2"<<endl;
 }

 
static int test3()
 
{
  cout
<<"this is test3"<<endl;
  
return 1;
 }

}
;

int  main()
{
 Test::Fun f;
 Test test;
 f 
= Test::test1;
 (test.
*f)(3);

 f 
= Test::test2;
 (test.
*f)(3);

 
int (*f3)();
 f3 
= Test::test3;
 f3();
 
return 0;
}


    因为静态成员函数的执行和类的对象无关,也没有隐藏的对象指针参数,使用时和普通的C函数指针一样。非静态成员函数,因为有隐藏的对象指针参数,执行时需要一个类对象。

在C语言中,内部函数指针即为指向内部成员函数的指针,而C函数指针则是指向普通的C函数的指针。在C语言中,实际上并没有内部的概念,只能通过结构体内的函数指针来模拟实现内部的成员函数的调用。 为了将内部函数指针转换为C函数指针,我们需要手动维护一个指向内部实例的指针,并将其作为第一个参数传递给内部函数。这样,我们可以通过将内部实例的指针与内部函数指针一起传递给C函数,来模拟内部函数的调用。 下面是一个简单的示例代码,演示了如何将内部函数指针转换为C函数指针: ```c #include <stdio.h> // 内部的定义 typedef struct { int x; int y; void (*add)(int, int, void*); } InnerClass; // 内部的成员函数 void add(int a, int b, void* instance) { InnerClass* innerInstance = (InnerClass*) instance; innerInstance->x += a; innerInstance->y += b; } // C函数,接收C函数指针作为参数 void callCFunction(void (*cFuncPtr)(int, int, void*), void* instance) { cFuncPtr(10, 20, instance); } int main() { InnerClass innerInstance; innerInstance.x = 0; innerInstance.y = 0; innerInstance.add = add; printf("Before call: x = %d, y = %d\n", innerInstance.x, innerInstance.y); // 将内部函数指针转换为C函数指针进行调用 callCFunction(innerInstance.add, &innerInstance); printf("After call: x = %d, y = %d\n", innerInstance.x, innerInstance.y); return 0; } ``` 在上述示例中,我们定义了一个名为`InnerClass`的内部,其中包含了整型的成员变量`x`和`y`,以及一个函数指针`add`。`add`函数用于将传入的两个参数与内部的成员变量相加。 然后,我们定义了一个名为`callCFunction`的C函数,其中接收一个C函数指针和一个内部实例的指针作为参数。在该函数中,我们通过调用传入的C函数指针来调用内部函数,将`10`和`20`作为参数传递给内部函数。 在`main`函数中,我们创建了一个`InnerClass`的实例`innerInstance`,并将其成员变量`x`和`y`初始化为`0`。接着,我们调用了`callCFunction`函数,将内部函数指针`innerInstance.add`和`&innerInstance`作为参数传递给它。 最后,我们在控制台上输出了内部函数调用前后的`x`和`y`的值,可以看到内部函数的调用对内部实例的成员变量进行了修改。这就说明我们成功将内部函数指针转换为C函数指针,并通过C函数的调用来模拟了对内部函数的调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值