在C ++中,为什么struct实际上是类? [英] In C++, why struct is in fact class?
问题描述
其他主题和响应让我问这个问题:
The other topic and responses there made me ask this question:
为什么C ++允许 struct
的行为就像 class
?一方面,C ++通过使其成员默认为公共的(与C中一样)与 C-struct
兼容,通过允许它继承自类,并应用其他面向对象的技术(不再像 C-struct
),它使它看起来类。为什么它不会使它只是普通的 C-struct
没有OOP?任何特殊原因?
Why does C++ allow struct
to behave just like class
? At one hand, C++ made it compatible with C-struct
by making it's members public by default (just like in C), while on the other hand, it made it look-like class by allowing it to be inherited from classes, and applying other object-oriented techniques (not so much like C-struct
anymore). Why did it not make it just plain old C-struct
with no OOP? Any special reason?
推荐答案
从语言的角度看, / em>只是类的类型。它使得语言规范更简单,如果有较少的概念(用小字母'c'),它也使指定的语言更不容易出错,因为它不容易错过某些明显出来,如果每个共同的属性必须说明对于结构,联合和非结构,非联合类。
From a language point of view, structures and unions are just types of class. It makes the language specification simpler if there are fewer concepts (with a small letter 'c') and it also makes specifying the language less error prone as it is less easy to miss something 'obvious' out if every common property had to spelled out for each of structures, unions and non-structure, non-union classes.
C ++类有很多的潜在功能超过C结构,但作为C结构可以看作是一个退化的C ++类,它是最简单的,让他们正是这样。拥有特殊的结构概念以及类概念没有任何好处。
C++ classes have a lot of potential functionality over C structures but as C structures can be viewed as a degenerate C++ class, it is simplest to allow them to be exactly this. There is no benefit to having a special structure concept as well as a class concept.
从ISO / IEC 14882:2003,9 [class] / 4:
From ISO/IEC 14882:2003, 9 [class] / 4:
结构 > class-key
struct
;其成员和基类默认是公共的。 其成员默认是公开的,并且一次只能有一个数据成员。
A structure is a class defined with the class-key
struct
; its members and base classes are public by default. A union is a class defined with the class-keyunion
; its members are public by default and it holds only one data member at a time.
这篇关于在C ++中,为什么struct实际上是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!