C++ 如何通过成员函数指针调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12189057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call through a member function pointer?
提问by Nayana Adassuriya
I'm trying to do some testing with member function pointer. What is wrong with this code? The bigCat.*pcat();
statement doesn't compile.
我正在尝试使用成员函数指针进行一些测试。这段代码有什么问题?该bigCat.*pcat();
语句无法编译。
class cat {
public:
void walk() {
printf("cat is walking \n");
}
};
int main(){
cat bigCat;
void (cat::*pcat)();
pcat = &cat::walk;
bigCat.*pcat();
}
回答by James McNellis
More parentheses are required:
需要更多括号:
(bigCat.*pcat)();
^ ^
The function call (()
) has higher precedence than the pointer-to-member binding operator (.*
). The unary operators have higher precedence than the binary operators.
函数调用 ( ()
) 的优先级高于成员指针绑定运算符 ( .*
)。一元运算符的优先级高于二元运算符。