这个问题已经在c# /. net上下文中提出过了。

现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。

我将从一个明显的区别开始:

如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。

我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。


当前回答

虽然其他答案暗示了这一点,但并没有明确提到——结构体是与C兼容的,这取决于用法;课程不是。

这意味着如果你想要编写一个与C兼容的头文件,那么除了struct(在C世界中不能有函数;但可以有函数指针)。

其他回答

还有一个不成文的规则告诉我们: 如果类的数据成员与自身没有关联,则使用struct。 如果数据成员的值依赖于另一个数据成员的值,则使用class。

f.e

class Time
{
    int minutes;
    int seconds;
}

struct Sizes
{
    int length;
    int width;
};

唯一的其他区别是类和结构的默认继承,不出意外,它们分别是私有和公共的。

规范里没有,没有。主要的区别在于程序员在2年内阅读你的代码时的期望。结构体通常被假定为POD。当您为定义对象以外的目的定义类型时,也会在模板元编程中使用结构。

c++的起源和与C的兼容性是值得记住的。

C语言有结构体,它没有封装的概念,所以一切都是公共的。

在采用面向对象的方法时,默认为public通常被认为是一个坏主意,所以在编写一种原生有利于OOP(你可以在C中做OO,但它不会帮助你)的C形式时,这是c++(最初是“C With Classes”)的想法,默认为private成员是有意义的。

另一方面,如果Stroustrup改变了struct的语义,使其成员默认为私有,那么就会破坏兼容性(随着标准的分歧,这种情况不再经常发生,但所有有效的C程序也是有效的c++程序,这对c++的立足点有很大影响)。

因此引入了一个新的关键字class,它与struct完全相似,但默认为private。

如果c++从零开始,没有历史,那么它可能只有一个这样的关键字。它也可能不会产生这样的影响。

一般来说,人们在做类似C语言中使用结构体的事情时,会倾向于使用结构体;公共成员,没有构造函数(只要它不在联合中,你可以在结构中有构造函数,就像类一样,但人们倾向于不这样做),没有虚方法,等等。因为语言既可以用来指导机器,也可以用来与阅读代码的人交流(否则我们就会坚持使用汇编和原始VM操作码),所以坚持使用它是个好主意。

. In classes all the members by default are private but in structure members are public by default. There is no term like constructor and destructor for structs, but for class compiler creates default if you don't provide. Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should typically be used for grouping data. The class default access type is private, and the default mode for inheritance is private. A class should be used for grouping data and methods that operate on that data. In short, the convention is to use struct when the purpose is to group data, and use classes when we require data abstraction and, perhaps inheritance. In C++ structures and classes are passed by value, unless explicitly de-referenced. In other languages classes and structures may have distinct semantics - ie. objects (instances of classes) may be passed by reference and structures may be passed by value. Note: There are comments associated with this question. See the discussion page to add to the conversation.