<分区>
Possible Duplicate:
What are the differences between struct and class in C++
我已完成作业并在 Google 上得到了不同的答案。
有人说结构没有继承,有人说结构没有访问说明符,还有人说两者都有。
那么有人可以澄清一下 C 和 C++ 中结构和类之间的区别,以及 C 和 C++ 中结构之间的区别。
<分区>
Possible Duplicate:
What are the differences between struct and class in C++
我已完成作业并在 Google 上得到了不同的答案。
有人说结构没有继承,有人说结构没有访问说明符,还有人说两者都有。
那么有人可以澄清一下 C 和 C++ 中结构和类之间的区别,以及 C 和 C++ 中结构之间的区别。
最佳答案
在 C++ 中,结构和类之间的唯一区别是结构成员默认是公共(public)的,而类成员默认是私有(private)的。
但是,作为一种风格,最好将 struct
关键字用于 C 中合理的结构(或多或少的 POD 类型),和 class
关键字(如果它使用 C++ 特定的功能,例如继承和成员函数)。
C 没有类。
C 结构不能使用 C++ 特定的功能。
编辑:
C++ FAQ Lite ,问题 7.9,有这样的话:
The members and base classes of a
struct
arepublic
by default, while inclass
, they default toprivate
. Note: you should make your base classes explicitlypublic
,private
, orprotected
, rather than relying on the defaults.
struct
andclass
are otherwise functionally equivalent.OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a
class
and astruct
. Astruct
simply feels like an open pile of bits with very little in the way of encapsulation or functionality. Aclass
feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use thestruct
keyword if you have a class that has very few methods and haspublic
data (such things do exist in well designed systems!), but otherwise you should probably use theclass
keyword.
并引用 Stroustrup 的“The C++ Programming Language”,第 4 版,第 16.2.4 节:
These two definitions of S are interchangeable, though it is usually wise to stick to one style. Which style you use depends on circumstances and taste. I tend to use struct for classes that I think of as "just simple data structures." If I think of a class as "a proper type with an invariant," I use class. Constructors and access functions can be quite useful even for *struct*s, but as a shorthand rather than guarantors of invariants.
关于c++ - 结构体和类的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7762085/