Java如何替换switch顺序执行_函数指针如何替换switch语句?

我正在阅读这个关于函数指针的教程,它说函数指针可以替换switch语句http://www.newty.de/fpt/intro.html .

任何人都可以澄清吗?

我们有一个这样的switch语句:

// The four arithmetic operations ... one of these functions is selected

// at runtime with a swicth or a function pointer

float Plus (float a, float b) { return a+b; }

float Minus (float a, float b) { return a-b; }

float Multiply(float a, float b) { return a*b; }

float Divide (float a, float b) { return a/b; }

// Solution with a switch-statement - specifies which operation to execute

void Switch(float a, float b, char opCode)

{

float result;

// execute operation

switch(opCode)

{

case '+' : result = Plus (a, b); break;

case '-' : result = Minus (a, b); break;

case '*' : result = Multiply (a, b); break;

case '/' : result = Divide (a, b); break;

}

cout << "Switch: 2+5=" << result << endl; // display result

}

// Solution with a function pointer - is a function pointer and points to

// a function which takes two floats and returns a float. The function pointer

// "specifies" which operation shall be executed.

void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))

{

float result = pt2Func(a, b); // call using function pointer

cout << "Switch replaced by function pointer: 2-5="; // display result

cout << result << endl;

}

// Execute example code

void Replace_A_Switch()

{

cout << endl << "Executing function 'Replace_A_Switch'" << endl;

Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');

Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);

}

如您所见,Replace_A_Switch()函数作为示例非常不清楚 . 假设我们需要将函数指针指向4个算术函数之一(Plus,Mins,Multiply,Divide) . 我们怎么知道我们需要指出哪一个?我们必须再次使用switch语句将函数指针指向算术函数,对吧?

这将是这样的**(请在代码中的评论)**:

void Replace_A_Switch()

{

.....................

..........

//How can we know this will point to the &Minus function if we don't use the switch statement outside?

Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);

}

所以综上所述,函数指针的优点是什么,它总是说函数指针是一种后期绑定机制,但是在本教程中我没有看到函数指针有任何优势,可以用于后期绑定 . 任何帮助都非常感谢 . 谢谢 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值