为什么 C 需要“struct"?关键字而不是 C++?
我一直对这里发生的事情感到有些困惑:
I've always been a little confused about what's going on here:
#include <stdio.h>
int main() {
timeval tv;
tv.tv_sec = 1;
for (;;) {
select(0, 0, 0, 0, &tv);
printf("%s
", "Hello World!");
}
}
对不起,如果没有编译,只是写它作为一个简单的例子.
Sorry if that doesn't compile, just wrote it as a quick example.
除非我在使用 struct timeval 之前添加关键字 struct,否则这样的代码不会在 gcc 下编译.另一方面,g++ 可以很好地处理它.
Code like this won't compile under gcc unless I add the keyword struct prior to the use of the struct timeval. g++ on the other hand handles it fine as is.
这是 C 和 C++ 处理结构的方式之间的差异,还是仅仅是编译器的差异?(我非常面向 C++,像这样在 C 语言中使用 struct 总是让我有些困惑).
Is this a difference between how C and C++ handle structures or is it just a difference in the compilers? (I'm very C++ oriented, and the use of struct in C on lines like this has always somewhat baffled me).
推荐答案
在语法上两者对 struct
的处理几乎相同.只有 C++ 添加了一个额外的规则,允许在没有歧义的情况下省略 struct
(和 class
)关键字.
Syntactically both treat struct
almost the same. Only C++ has added an extra rule that allows to omit the struct
(and class
) keyword if there is no ambiguity.
如果有歧义,C++ 在某些地方也需要 struct
关键字.一个臭名昭著的例子是 POSIX 系统上的 stat
,其中有一个 struct stat
和一个函数 stat
.
If there is ambiguity, also C++ requires the struct
keyword in some places. A notorious example is stat
on POSIX systems where there is a struct stat
and a function stat
.
相关文章