C语言函数指针的例子

来源:互联网 发布:淘宝一元拍网址 编辑:程序博客网 时间:2024/05/01 01:48
#include <iostream>
using namespace std;
 
//定义一个类型别名 Fuction:参数为int,返回值为void
typedef void(*Fuction)(int);
 
void positive(int n)
{
  cout <<n <<"is a positive number" << endl;
}
 
void negative(int n)
{
  cout << n<<" is a negative number" << endl;
}
 
void zero(int n)
{
  cout << n << " is zero" << endl;
}
 
void testCallBack(int n,Fuction *PF)
{
  if (n==0)
  {
    *PF = zero;
  }else if (n > 0)
  {
    *PF = positive;
  }
  else
  {
    *PF = negative;
  }
 
  (*PF)(n);
}
 
int main()
{
  Fuction  mFuction;      //声明一个函数指针。    
  int a = 3;
  int b = 0;
  
  testCallBack(a, &mFuction);
  testCallBack(b, &mFuction);
 
  return 0;
}
0 0
原创粉丝点击