正如我们所知,struct
和 class
在该语言的许多地方是可以互换的。令人困惑的是,关键字本身不一定对应于标准中使用的语言。例如,在标准草案 N4567 [class]/10 中,
A POD struct109 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.
简单来说,struct
和 class
在以下情况下可以互换:
- “类”的声明
- 范围枚举类型的声明
- 详尽的类型说明符,除非“类”是用
union
声明的
但是,struct
明确地不能在模板声明中用来引入类型模板参数:
template <struct T> // error
即使在上面的 POD 示例中,我也看不出 struct
和 class
之间有任何显着差异,因为 POD struct 定义为在标准中可以用 struct
或 class
声明。
[class]/8 A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class. A standard-layout union is a standard-layout class defined with the class-key union.
在引入明显的不一致时,这似乎相当多余和令人困惑。
我有两个问题:
是否有任何我遗漏的显着区分
struct
和class
的技术差异?这种笨拙背后的基本原理是什么?
我忽略了默认访问说明符之间的区别,因为每个人都已经知道了。
最佳答案
Why do both struct and class exist in C++?
struct
存在的原因是为了与 C 兼容。
那么,为什么“C with Classes”引入了新关键字 class
什么时候可以使用 struct
对于同样的事情,你可能会问。看这个SO answer为了合理的推测。简而言之,这可能是因为希望强调OOP。其中class是一个广泛使用的术语。只有 Stroustrup 可能知道。
Confusingly, the keywords themselves do not necessarily correspond to the language used in the standard
需要理解的是,类 的概念与关键字class
不是一回事。 .
声明类的关键字有3个。这些称为类键的关键字是 class
, struct
和 union
.使用 class
声明的非 union 类或 struct
除了 † 之外,它们完全相同。 union 类不同于非 union 类。
However, struct explicitly cannot be used in a template declaration to introduce type template parameters
C++ 在不同的上下文中出于不同的目的重复使用关键字。 class
类声明上下文中的关键字,与 class
不完全相同模板参数定义中的关键字。一个关键字在一种上下文中等同于另一个关键字并不意味着它在所有上下文中都等同。在不同但相似的上下文中重用关键字的原因(static
是另一个例子)是为了避免引入新的关键字,这会引入更多与没有新关键字的 C(或更早的 C++ 标准)兼容的漏洞。
原因 class
关键字在模板类型参数的上下文中被重用可能是因为类是类型,因此通常用作类型参数。还有一个typename
关键字,这是后来添加的并且(几乎)可以与 class
互换。在模板类型参数声明中,但也用于其他地方(依赖类型名称),其中 class
未使用。看这个answer获取有关为什么将单独的关键字添加到该上下文的链接和摘要。
为什么 struct
在上下文中不作为等价物使用,你可能会问。那么,这是 Stroustrup 或委员会的另一个问题。这与委员会在 enum class
时所做的选择相反。/enum struct
被介绍。
I'm unable to see any significant difference between struct and class
很好。除了 †
之外没有任何其他内容This seems rather redundant and confusing while introducing a glaring inconsistency.
我发现标准中的引用没有不一致之处。我看到了冗余,我怀疑存在冗余是为了更加清楚地表明使用关键字 struct
声明的类仍然是一个类。
- Are there any technical differences that I have missed that significantly distinguish struct and class?
我已经回答了,但需要明确的是,用 struct
声明的类之间没有区别和 class
关键字,超越†。
† 与默认访问说明符的区别(如您所知,并且还描述了 here ),这是它们的唯一区别。
关于c++ - 为什么C++中同时存在struct和class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906229/