这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
当前回答
综上所述,我们可以得出结论,概念Class比“Structures”更适合代表现实世界中的对象。很大程度上是因为在课堂上使用的面向对象的概念在解释现实场景时非常实用,因此更容易将它们合并到现实中。例如,对于结构体,默认继承是公共的,但如果我们将此规则应用于现实世界,那就太荒谬了。但在类中,默认继承是私有的,这更现实。
无论如何,我需要证明的是类是一个更广泛的,现实世界适用的概念,而结构是一个原始的概念,具有糟糕的内部组织(即使结构遵循面向对象的概念,他们有一个糟糕的含义)
其他回答
类的成员默认为private。Struct的成员默认为public。除此之外,没有其他区别。还有这个问题。
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不支持!
根据c++编程语言中的Stroustrup:
你使用哪种风格取决于环境和品味。对于所有数据都是公共的类,我通常更喜欢使用struct。我认为这样的类“不是很合适的类型,只是数据结构”。
在功能上,除了public / private没有区别
类只有在软件工程上下文中才有意义。在数据结构和算法的上下文中,类和结构并没有那么大的不同。没有任何规则限制必须引用类的成员。
当与大量的人一起开发大型项目时,你可能最终会得到复杂的耦合代码,因为每个人都使用他们想要的函数和数据。类提供权限控制和固有属性,以增强代码的解耦和重用。
如果您阅读了一些软件工程原理,就会发现没有类,大多数标准都无法轻松实现。例如: http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29
顺便说一句,当一个struct分配了大量内存并包含了几个变量时,值类型变量表示值嵌入到struct分配的位置。相比之下,引用类型变量的值是外部的,由一个指针引用,该指针也嵌入在struct分配的地方。
. 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.