int (*fp)(int a);//这里就定义了一个指向函数的指针 。初学C++ ,以代码作为学习笔记。

/函数指针
/******************************************************************************************
#include "stdafx.h"
#include <iostream> 
#include <string> 
using namespace std; 

int test(int a); 

int _tmain(int argc,_TCHAR* argv[])   

 cout << test << endl;//显示函数地址 
 int (*fp)(int a); 
 fp = test;//将函数test的地址赋给函数学指针fp 
 cout << fp(5) << "|" << (*fp)(10) << endl; 
 //上面的输出fp(5),这是标准c++的写法,(*fp)(10)这是兼容c语言的标准写法,两种同意,但注意区分,避免写的程序产生移植性问题! 
 return 0;

int test(int a) 

 return a; 
}
******************************************************************************************/
//函数指针,以typedef 形式定义了一个函数指针类型
/******************************************************************************************
#include "stdafx.h"
#include <iostream> 
#include <string> 

using namespace std; 

int test(int a); 

int _tmain(int argc,_TCHAR* argv[])   

 cout<<test<<endl; 
 typedef int (*fp)(int a);//注意,这里不是生命函数指针,而是定义一个函数指针的类型,这个类型是自己定义的,类型名为fp 
 fp fpi;//这里利用自己定义的类型名fp定义了一个fpi的函数指针! 
 fpi=test; 
 cout<<fpi(5)<<"|"<<(*fpi)(10)<<endl; 
 return 0;

int test(int a) 

 return a; 
}
******************************************************************************************/
//函数指针作为参数的情形。
/******************************************************************************************
#include "stdafx.h"
#include <iostream>   
#include <string>

using namespace std;   

int test(int);   

int test2(int (*ra)(int),int); 

int _tmain(int argc,_TCHAR* argv[])     
{   
 cout << test << endl; 
 typedef int (*fp)(int);   
 fp fpi; 
 fpi = test;//fpi赋予test 函数的内存地址 

 cout << test2(fpi,1) << endl;//这里调用test2函数的时候,这里把fpi所存储的函数地址(test的函数地址)传递了给test2的第一个形参 
 return 0;
}   

int test(int a) 
{   
 return a-1; 

int test2(int (*ra)(int),int b)//这里定义了一个名字为ra的函数指针 

 int c = ra(10)+b;//在调用之后,ra已经指向fpi所指向的函数地址即test函数 
 return c; 
}
******************************************************************************************/
#include "stdafx.h"
#include <iostream>   
#include <string>   
using namespace std; 

void t1(){cout<<"test1";} 
void t2(){cout<<"test2";} 
void t3(){cout<<"test3";} 
int _tmain(int argc,_TCHAR* argv[])     

 void* a[]={t1,t2,t3}; 
 cout<<"比较t1()的内存地址和数组a[0]所存储的地址是否一致"<<t1<<"|"<<a[0]<<endl; 

 //cout<<a[0]();//错误!指针数组是不能利用数组下标操作调用函数的 

 typedef void (*fp)();//自定义一个函数指针类型 
 fp b[]={t1,t2,t3}; //利用自定义类型fp把b[]定义趁一个指向函数的指针数组 
 b[0]();//现在利用指向函数的指针数组进行下标操作就可以进行函数的间接调用了; 
 return 0;
}

posted on 2008-04-08 23:38 -274°C 阅读(272) 评论(1)  编辑  收藏 所属分类: C++


FeedBack:
# re: C++ 之函数指针
2008-12-22 10:38 | @
//typedef int pHelloWorld();
//pHelloWorld *pHello = (pHelloWorld *)::GetProcAddress(hDll, "HelloWorld");
typedef int (*pHelloWorld)();
pHelloWorld pHello = (pHelloWorld)::GetProcAddress(hDll, "HelloWorld");
  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

常用链接

留言簿(21)

随笔分类(265)

随笔档案(242)

相册

JAVA网站

关注的Blog

搜索

  •  

积分与排名

  • 积分 - 909071
  • 排名 - 40

最新评论