在 C 中,结构的标签与其他标识符位于不同的命名空间中。因此,除非引入别名,否则他们必须写struct T
为类型名称。在 C++ 中(其中class
and struct
具有相同的基本概念)它是为了自动将标签作为常规标识符引入的。
然而,C 语言中的一种行为必须加以考虑。你可以有这样的东西:
struct prettyThing
{
// data
};
void prettyThing();
由于命名空间不同,因此不存在歧义。所以 C++ 保留了这种行为。还可以有:
class prettyThing
{
// members
};
void prettyThing();
毫无疑问,类名被其他标识符隐藏。它只能通过详细类型说明符访问,即class prettyThing
。这就是为什么人们可能会像您所看到的那样编写声明的一个实际原因。这不是学术性的,考虑一下 POSIXstat and struct stat pair https://pubs.opengroup.org/onlinepubs/007904875/functions/stat.html.
但是...除非您与最初以 C 概念编写的 C 代码进行交互,否则没有理由以这种方式编写新的 C++ 代码。
人们可能想知道为什么它声明的类型不保持相同struct
并且根本不允许使用声明的类型class
。要理解这一点,最好重申并记住这一点class
es and struct
ures 在 C++ 中实际上意味着相同的东西(除了默认访问说明符)。以下都是有效的 C++:
struct thing1; // forward declare
class thing1 {
// define
};
struct thing2 {
// define
};
class thing2 object;
Either keyword can be used in the elaborated-type-specifier, they are completely interchangeable in standard C++1.
1 - Microsoft ABI behaves as a bit of an oddball here, though https://stackoverflow.com/questions/40738351/forward-declaration-as-struct-vs-class.