如何让 test.calculate 中的函数指针赋值(可能还有其他)起作用?
#include <iostream>
class test {
int a;
int b;
int add (){
return a + b;
}
int multiply (){
return a*b;
}
public:
int calculate (char operatr, int operand1, int operand2){
int (*opPtr)() = NULL;
a = operand1;
b = operand2;
if (operatr == '+')
opPtr = this.*add;
if (operatr == '*')
opPtr = this.*multiply;
return opPtr();
}
};
int main(){
test t;
std::cout << t.calculate ('+', 2, 3);
}
最佳答案
您的代码有几个问题。
首先,int (*opPtr)() = NULL;
不是指向成员函数的指针,而是指向自由函数的指针。像这样声明一个成员函数指针:
int (test::*opPtr)() = NULL;
其次,在取成员函数的地址时需要指定类作用域,如下所示:
if (operatr == '+') opPtr = &test::add;
if (operatr == '*') opPtr = &test::multiply;
最后,通过成员函数指针调用,有特殊语法:
return (this->*opPtr)();
这是一个完整的工作示例:
#include <iostream>
class test {
int a;
int b;
int add (){
return a + b;
}
int multiply (){
return a*b;
}
public:
int calculate (char operatr, int operand1, int operand2){
int (test::*opPtr)() = NULL;
a = operand1;
b = operand2;
if (operatr == '+') opPtr = &test::add;
if (operatr == '*') opPtr = &test::multiply;
return (this->*opPtr)();
}
};
int main(){
test t;
std::cout << t.calculate ('+', 2, 3);
}
关于c++ - 将 C++ 函数指针分配给同一对象的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864341/