分配 C++指向同一对象的成员函数的函数指针
如何让 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);
}
How do I get the function pointer assignments (and maybe the rest) in test.calculate to work?
#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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码存在几个问题。
首先,int (*opPtr)() = NULL; 不是指向成员函数的指针,而是指向自由函数的指针。像这样声明一个成员函数指针:
int (test::*opPtr)() = NULL;
其次,在获取成员地址时需要指定类作用域函数,如下所示:
最后,要通过成员函数指针进行调用,有特殊的语法:
这是一个完整的工作示例:
There are several problems with your code.
First,
int (*opPtr)() = NULL;
isn't a pointer to a member function, its a pointer to a free function. Declare a member function pointer like this:int (test::*opPtr)() = NULL;
Second, you need to specify class scope when taking the address of a member function, like this:
Finally, to call through a member function pointer, there is special syntax:
Here is a complete working example:
就像这个
int (test::*opPtr)() = NULL;
。请参阅http://www.parashift.com/ c++-faq-lite/pointers-to-members.html#faq-33.1编辑:还可以使用
if (operatr == '+') opPtr = &test::add;
而不是[..] = this.add
和return (this->
(opPtr ))();
而不是return opPtr();
。事实上,使用常见问题解答中提到的 typedef 和宏,以及可能的成员函数参数,而不是类成员a
和b
。Like this
int (test::*opPtr)() = NULL;
. Refer http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1Edit: Also use
if (operatr == '+') opPtr = &test::add;
instead of[..] = this.add
andreturn (this->
(opPtr))();
instead ofreturn opPtr();
. In fact, use typedefs and macros like the FAQ says and probably member function paramaters instead of class membersa
andb
.