如何使用函数指针调用函数? [英] How can I call a function using a function pointer?

查看:161
本文介绍了如何使用函数指针调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下三个功能:

Suppose I have these three functions:

bool A();
bool B();
bool C();

如何使用函数指针有条件地调用这些函数之一,以及如何声明函数指针?

How do I call one of these functions conditionally using a function pointer, and how do I declare the function pointer?

推荐答案

您可以执行以下操作: 假设您有A,B和C函数如下:

You can do the following: Suppose you have your A,B & C function as the following:

bool A()
{
   .....
}

bool B()
{
   .....
}

bool C()
{

 .....
}

现在使用其他功能,例如在main上说

Now at some other function, say at main:

int main()
{
  bool (*choice) ();

  // now if there is if-else statement for making "choice" to 
  // point at a particular function then proceed as following

  if ( x == 1 )
   choice = A;

  else if ( x == 2 )
   choice = B;


  else
   choice = C;

if(choice())
 printf("Success\n");

else
 printf("Failure\n");

.........
  .........
  }

请记住,这是函数指针的一个示例.还有其他几种方法,您必须清楚地学习函数指针.

Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.

这篇关于如何使用函数指针调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆