【发布时间】:2014-10-16 06:06:27
【问题描述】:
我正在阅读有关函数指针的教程,它说函数指针可以替换 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 - <opCode> 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 - <pt2Func> 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);
}
所以总结一下,函数指针的优点是什么,总是说函数指针是一种后期绑定机制,但是在本教程中我没有看到函数指针对于后期绑定的任何优势。 非常感谢任何帮助。谢谢。
【问题讨论】:
-
简而言之,您需要一个函数指针数组,可以按您的操作码类型进行索引。由于您的索引是
char而不是一些合成字节码,这意味着 256 个元素,请记住将索引转换为unsigned char。 -
鉴于您使用 C++ 进行编码,为什么不使用带有虚拟方法的类层次结构,让编译器担心这一切的机制?
-
@NPE 因为,虽然抽象很好,但也会导致 VM 速度慢(相对)......这也与探索这种方法的目的背道而驰。
-
虚函数并不比函数指针快或慢。函数指针就是虚函数。
标签: c++ c pointers function-pointers