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

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

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

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

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


当前回答

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

其他回答

struct和class之间的主要区别是,在struct中只能声明不同数据类型的数据变量,而在class中可以声明数据变量和成员函数,因此可以通过函数操作数据变量。

-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it . while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..

但这取决于程序员认为哪种方式合适……对我来说,我更喜欢类,因为它支持oop,这就是它几乎在所有语言中实现的原因,它是所有编程的美妙特性;-)

是的,我忘记提到的最令人难忘的区别是类支持数据隐藏,也支持在内置数据类型上执行的操作,而struct不支持!

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

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

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

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

引用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++编程语言中的Stroustrup:

你使用哪种风格取决于环境和品味。对于所有数据都是公共的类,我通常更喜欢使用struct。我认为这样的类“不是很合适的类型,只是数据结构”。

在功能上,除了public / private没有区别

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

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

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

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

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

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