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

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

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

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

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


当前回答

Iso iec14882 -2003 9类 §3 结构是用定义的类 类键结构体;它的成员 基类(第10条)是 默认为公开(第11条)。

其他回答

引用c++ FAQ,

[7.8] What's the difference between the keywords struct and class? 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.

c++中struct和class关键字的区别在于,当在特定的复合数据类型上没有特定的说明符时,默认情况下struct或union是只考虑隐藏数据的公共关键字,而class是考虑隐藏程序代码或数据的私有关键字。总是有一些程序员为了数据而使用结构,为了代码而使用类。欲了解更多信息,请联系其他渠道。

结构和类之间有3个基本区别

第1 -内存是为堆栈内存中的结构保留的(这接近于编程语言),无论堆栈内存中的类是仅为引用保留的,实际内存是在堆内存中保留的。

默认情况下,结构对待公共类是否对待私有类。

第三,不能在结构中重用代码,但在类中我们可以多次重用相同的代码,称为继承

oops中structure和class关键字的主要区别在于,structure中没有public和private成员声明。数据成员和成员函数可以定义为public、private和protected。

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