c/c++函数指针数组应用
来源:互联网 发布:orico网络储存器怎么用 编辑:程序博客网 时间:2024/05/19 18:00
C语言里我们学过函数、指针、数组。
为解决实际的应用过程中出现的问题。
什么问题呢?如下:
void MyTestFuntion(int length )
{
switch( length )
{
case 0:
function1();
break;
case 1:
......
break;
case 255:
function255();
break;
}
}
//以上代码完成了一个模拟的功能即根据输入参数的不同,进行不同的处理.
这段代码表面看似风平浪静,可以完成功能.但是效率不高。需要进行多次判断.
PC上没有问题,假如针对嵌入式设备,这样做可能会影响效率.
计算一下此函数有700多行,浪费设备空间了. 就是一个“小胖”函数. 哈哈哈.
针对以上的应用,我们可以使用“函数指针数组”处理. 让它减肥
下面针对两种情况说明:
一、C语言
#include "stdafx.h"
void function0(void);
void function1(void);
void function2(void);
void MyTestFuntion(int length);
void (*fun[])(void) = {
function0,
function1,
function2
};
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
MyTestFuntion(1);
return 0;
}
void function0(void){
//this is function 0
}
void function1(void){
//this is function 1
}
void function2(void){
//this is function 2
}
void MyTestFuntion(int length)
{
(*fun[length])();
}
以上最基本的用法了. 通过使用函数指针数组将函数MyTestFuntion轻松减肥.
二、C++
TestClass.h
typedef void (*fun)(void);
class CTestClass
{
public:
CTestClass();
virtual ~CTestClass();
static void function0(void); //一定要是static啊!static函数不会
传递“this”指针
static void function1(void); //其他的非static函数,会有一个隐形
的翅膀“this”
static void function2(void); //导致为数组赋初值时类型不匹
配...........
void MyTestFuntion(int length);
public:
fun apfun[3];
};
TestClass.cpp
CWinApp theApp;
using namespace std;
#include <string>
#include <iostream>
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
CTestClass Ctest;
Ctest.MyTestFuntion(1);
return 1;
}
CTestClass::CTestClass(
){
apfun[0] = function0;
apfun[1] = function1;
apfun[2] = function2;
}
CTestClass::~CTestClass(
){
}
void CTestClass::function0(
){
//this is function 0
}
void CTestClass::function1(
){
//this is function 1
}
void CTestClass::function2(
){
//this is function 2
}
void CTestClass::MyTestFuntion(int length
){
(*apfun[length])();
}
以上:由一个体型很好的函数出现了.......哈哈
以上:apls
- c/c++函数指针数组应用
- C/C++函数指针数组应用
- [C]函数指针数组
- C 函数指针数组
- C函数指针数组
- [C学习]函数,指针,数组
- C语言:数组 指针 函数
- c有关函数指针数组
- C语言函数指针数组
- 【C语言】函数,函数指针;指针数组,数组指针。
- [C++] 函数指针的应用
- [c/c++]如何声明函数指针数组
- C语言_函数指针数组指针
- 【C语言】理解指针数组 数组指针 函数指针
- C语言中的指针(指针数组 数组指针 函数指针 函数指针数组 指向函数指针数组的指针)
- C程序设计语言--指针与数组(二) 指针数组 数组指针 函数指针 指针函数
- 指针, 指针的指针, 数组, 指针数组, 数组指针, 指针函数, 函数指针 C/C++中函数指针的含义
- c语言数组指针的应用
- 优化Oracle网络设置的方案
- 深入浅出谈CUDA
- Apache Java项目全介绍
- 使用智能优化器提高Oracle的性能极限
- 想要精通PHP吗?先学好Linux/Unix和C吧
- c/c++函数指针数组应用
- Oracle索引分析与比较
- Oracle 数据库优化的R方法(Method R)
- Oracle专家调优秘密
- 确立 注释规范
- GPRS开发系列文章之入门篇
- JPA
- 用友架构调整:U9、CRM及e-HR独立为事业部
- Struts2: 使用s:iterator标记输出Map、List、Array容器组合的数据结构