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

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

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

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

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


当前回答

你忘记了类和结构之间棘手的第二个区别。

引用标准(§11.2.2在c++ 98到c++ 11):

在没有访问说明符时 对于基类,假定为public 当声明派生类时 Struct和private在类声明为class时被假设。

为了完整起见,更广为人知的class和struct之间的区别定义在(11.2)中:

类定义的类的成员 关键字类private by 违约。定义的类的成员 使用关键字struct或union 默认为public。

另一个区别是:关键字class可以用来声明模板参数,而struct关键字不能这样使用。

其他回答

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

这里有一个很好的解释:http://carcino.gen.nz/tech/cpp/struct_vs_class.php

所以,再强调一次:在c++中,结构体与类是相同的,除了结构体的成员默认具有公共可见性,而类的成员默认具有私有可见性。

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

. 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.

我发现了另一个不同。如果在类中没有定义构造函数,编译器将定义一个。但是在struct中,如果你没有定义构造函数,编译器也不会定义构造函数。因此,在某些情况下,我们确实不需要构造函数,struct是一个更好的选择(性能技巧)。 对不起,我的英语不好。