解释使用意外声明为函数的对象后出现的 GCC 错误
以下是语言新手常见的错别字,他们认为自己在定义一个对象,但实际上是在声明一个函数:
struct T
{
void foo() {}
};
int main()
{
T obj();
obj.foo();
}
GCC 4.1.2 的错误是:
In function 'int main()':
Line 9: error: request for member 'foo' in 'obj', which is of non-class type 'T ()()'
compilation terminated due to -Wfatal-errors.
为什么消息中报告的类型是 T ()()?我本来期望的是
T ()
。
The following is a common typo with language newcomers, who think that they are defining an object but are actually declaring a function:
struct T
{
void foo() {}
};
int main()
{
T obj();
obj.foo();
}
GCC 4.1.2's error is:
In function 'int main()':
Line 9: error: request for member 'foo' in 'obj', which is of non-class type 'T ()()'
compilation terminated due to -Wfatal-errors.
Why is the reported type in the message T ()()
? I'd have expected T ()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IIRC 这只是一个编译器错误。 GCC 4.4 对我来说是
T()
而 4.2 是T()()
。IIRC this is just a compiler bug. GCC 4.4 says
T()
while 4.2 saysT()()
for me.当您意识到通常不会在不命名函数的情况下写出函数类型时,就可以最好地理解该错误,但对于函数指针来说,这种情况更为常见。
例如,
int (*fooPtr)()
命名指针。如果省略名称,则为int (*)()
。现在,从函数指针到函数类型将得到int ()()
。这里没有真正的标准,因为 ISO C++ 没有为所有类型定义规范名称。例如,
const volatile int
与volatile const int
类型相同,并且两种形式都不是规范的。The error is best understood when you realize that you usually don't write out function types without naming at least the function, but it's a bit more common for function pointers.
For instance,
int (*fooPtr)()
names the pointer. If you omit the name, you haveint (*)()
. Now, going from function pointer to function type would give youint ()()
.There's no real standard here, because ISO C++ doesn't define canonical names for all types. For instance,
const volatile int
is the same type asvolatile const int
, and neither form is canonical.