c++ - 结构体和类的区别

标签 c++ struct

<分区>

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 are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class 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 the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class 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/

相关文章:

Swift 3 单元测试抛出编译错误 "Cannot convert value ' Type' to 'Type' "

ios - 释放结构时出错

c# - 从 64 位应用程序调用 32 位 DLL 的函数

c++ - 使用 <algorithm> 对结构 vector 进行排序

c++ - for 循环 : poor efficiency in my code 的 OpenMP 并行化

c++ - 将在类中声明的函数作为参数传递会导致编译错误

c++ - 带字符串的链表

c - 在C语言中,单元测试应该写在Header文件中还是C文件中

c++ - 在 C++ 中将值作为常量、引用和常量引用返回的含义是什么?

c++ - 向量化 (SIMD) 树操作