HeJ小鼠!我想学习使用C中函数的指针。所以我写了一个小计算器,包含私有操作的函数和一个指针,根据输入的操作符号切换它们。我不知道它是否会比调用单个函数更有效,但它只是一个测试。
因此,在Calculator类公共部分内部,此函数假设将POper
指针设置为适当的操作:
void Calculate() {
switch (m_s) {
default:
printf("Error, wrong operation sign\n");
break;
case '+':
POper = &Calculator::Add;
break;
case '-':
POper = &Calculator::Sub;
break;
case '*':
POper = &Calculator::Multi;
break;
case '/':
POper = &Calculator::Divide;
break;
}
}
当我尝试编译fallowing代码时,gcc给我这种类型的错误交战:
../src/main.cpp: In member function ‘void Calculator::Calculate()’:
../src/main.cpp:16:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
POper = &Calculator::Add;
^
../src/main.cpp:19:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
POper = &Calculator::Sub;
^
../src/main.cpp:22:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
POper = &Calculator::Multi;
^
../src/main.cpp:25:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
POper = &Calculator::Divide;
我真的不明白,POper
和使用成员都是Calculator类的一部分。这对cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
意味着什么?差异是什么?