看板Programming
标 题Re: [问题] 请问Function pointer阵列问题
发信站KKCITY (Thu Apr 3 13:27:48 2008)
转信站ptt!ctu-reader!ctu-gate!news.nctu!news.ncu!news.yzu!zoonews.ee.ntu!new
※ 引述《[email protected] (绿豆嘉义人)》之铭言:
> 小弟有个关於指标阵列的疑问
> 书上说指标阵列常拿来做选单系统, 不同的选项会呼叫不同的function
> 今天如果code如下
> // prototype
> void fun1 (int);
> void fun2 (int);
> void fun3 (int);
> // function pointer array
> void (*f[3]) (int) = {fun1, fun2, fun3};
> 这样是OK的
> 但是如果把fun2改成 void fun2 (int, int)
> 就会出现compile error (cannot convert from xxxxx)
> 也很明显的是函式的signature不合
> 所以我的疑问是
> 难道要用function pointer做到选单功能
> 每个选单功能的回传和接收的参数数目难道都要一样吗?
当然!
我问你,你的程式难道不会写成下面的样子?
scanf("%d", &op1);
scanf("%d", &op2);
scanf("%d", &opr);
res1=f[opr](op1, op2);
写成函数指标,就是希望evaluate叙述只要写一次,可以达到跟多条一样的
效果,所以每次传进去的参数都会一样。
而如果有一条以上的evaluate叙述
res1=f[opr](op1, op2);
resn=f[opr](op1);
那为何不分组,unioperand的函数归一个阵列,bioperand的函数另归一个阵列?
enum { uni, bi };
float (*opu[3])(float);
float (*opb[4])(float, float);
opu[0]=invert; opu[1]=sqrt; opu[2]=exp;
opb[0]=plus; opb[1]=minus; opb[2]=mul; opb[3]=div;
while (...) {
...
res = optype(opt) ? opu(op1) : opb(op1, op2);
...
}
一个selective evaluation就解决了。
> 这样一点也不弹性
鹿「弹性」变成马 ==> 马鹿
> 所以我想问, 请问有没有什麽办法可以解这个问题?
> 让阵列里面每个pointer都指到一个函式
> 而且那些函式也可以有不同的回传和接收参数数目
我必须要称赞你的想法真是无聊,给自己制造太多便利,增加发生错误的风险
不过当然是有办法可以解。(不然IOCCC要怎麽比?)
1: 使用 "..." function-list argument 实作变数。
2: 给每个unioperand的函数加虚参数,该参数没有用处,执行中也会忽略。
---
老话一句,抱怨某个feature以前,你真的用这个feature写过程式吗?你是
不是把鹿当马骑呢?
--
 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄
For the country must we secure all the advantages, but after the party!
ˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍˍ
─ journeyman ─
SCA v2
--
┌─────◆KKCITY◆─────┐ ◢
◤ 动态歌词 让你成为K歌之王!
│ bbs.kkcity.com.tw │ \^_^ / ★ http://www.kkbox.com.tw ★
└──《From:59.115.215.116
》──┘ ◤ 唱片公司授权,音乐尽情下载
--