6

可能重复:
C++中的struct和class有什么区别

我只是想弄清楚在 C++ 中使用“C 结构”是否基本上没用。您是否通过使用它们获得任何收益(与简单地创建另一个类相反)?

在 C 中,结构的意义是显而易见的,只是分组数据的连续分配和访问所述数据的好方法,在 C++ 中,我觉得角色变得更加模糊。

鉴于您可以拥有结构成员、实例变量和可见性标签的函数,我在 C++ 中看到的结构和类之间的唯一真正区别是结构成员默认为公共,而类成员默认为私有。在我看来,它们实际上都可以使用相同的底层系统来实现。

那么我在这里遗漏了关于 C++ 中结构的用途的内容吗?或者他们已经失去了他们的目的,就像我觉得他们在 C++ 中所做的那样?

4

6 回答 6

3

C++ 中的类和结构几乎相同,唯一不同的是,类的默认可见性是privatewhile 在结构中是public.

在 C++ 中保留结构的原因可能是为了保持语言与 C 兼容,因此将 C 代码移植到 C++ 会更容易,或者让程序员进行这种转换。

至于结构类的用法,我个人使用它们就像在 C 中一样,将相关变量组合在一个“对象”中。

于 2012-10-27T20:20:05.557 回答
3

在我看来,Structures 并没有给你任何类不能实现的东西。但是,结构保留在 C++ 中,以便与 c 向后兼容

于 2012-10-27T20:20:34.420 回答
2

Undoubtedly the reason they are there is for compatibility with C. But you are right, although there are small differences between class and struct in C++ there is nothing you can do with structs that you cannot do with classes (and vice versa).

Personally I use structs only when the same declaration would be legal in C, to emphasize the C-like nature of whatever it is I'm doing.

于 2012-10-27T20:22:02.363 回答
2

They are implemented "with the same exact underlying system". In fact, you can actually declare a type using class keyword and then define it using struct keyword. Basically, they are exactly the same aside from the conceptual difference you already mentioned: default access rights.

I don't see though why would one call them "useless". The usage of the keyword became a matter of personal preference and/or coding standard. Like "use struct fro POD types", or "use struct for types with no incapsulation/access control".

With the same degree of success one can declare the built-in -> operator "useless" because of its equivalence to *+. combination.

于 2012-10-27T20:22:56.183 回答
1

You can have the same behavior as in C, nobody forces you to use the additional "class" features. So if you understand their purpose in C, it should be understandable in C++ as well (the "C-like" portion at least).

于 2012-10-27T20:22:24.577 回答
1

As Joachim Pileborg already pointed out, classes and structures are almost the same thing in C++.

I would, however, recommend to use struct for "dumb" data holders with public members and class for properly encapsulated classes as a style convention.

于 2012-10-27T20:23:41.270 回答