带括号的成员函数地址错误
我发现了一些有趣的事情。错误消息说明了一切。获取非静态成员函数的地址时不允许使用括号的原因是什么?我在 gcc 4.3.4 上编译它。
#include <iostream>
class myfoo{
public:
int foo(int number){
return (number*10);
}
};
int main (int argc, char * const argv[]) {
int (myfoo::*fPtr)(int) = NULL;
fPtr = &(myfoo::foo); // main.cpp:14
return 0;
}
错误:main.cpp:14: 错误:ISO C++ 禁止采用未限定或带括号的非静态成员函数的地址来形成指向成员函数的指针。说“&myfoo::foo”
I found something interesting. The error message says it all. What is the reason behind not allowing parentheses while taking the address of a non-static member function? I compiled it on gcc 4.3.4.
#include <iostream>
class myfoo{
public:
int foo(int number){
return (number*10);
}
};
int main (int argc, char * const argv[]) {
int (myfoo::*fPtr)(int) = NULL;
fPtr = &(myfoo::foo); // main.cpp:14
return 0;
}
Error: main.cpp:14: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&myfoo::foo'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从错误消息来看,似乎不允许您获取带括号的表达式的地址。建议您重写
为
这是由于规范 (§5.3.1/3) 的一部分读取
(我的重点)。我不确定为什么这是一条规则(而且直到现在我才真正知道这一点),但这似乎是编译器抱怨的。
希望这有帮助!
From the error message, it looks like you're not allowed to take the address of a parenthesized expression. It's suggesting that you rewrite
to
This is due to a portion of the spec (§5.3.1/3) that reads
(my emphasis). I'm not sure why this is a rule (and I didn't actually know this until now), but this seems to be what the compiler is complaining about.
Hope this helps!
想象一下这段代码:
如果没有括号的技巧,您将无法直接获取 B 的数据成员的指针(您将需要基类转换和带有
this
的游戏 - 不太好)。来自ARM:
IS 只是保留了这个标准之前的概念,并明确提到括号使它这样你就不会没有得到指向成员的指针。
Imagine this code:
Without the trick with the parentheses, you would not be able to take a pointer directly to B's data member (you would need base-class casts and games with
this
- not nice).From the ARM:
The IS just kept this pre-Standard concept and explicitly mentioned that parentheses make it so that you don't get a pointer to member.