OOP 中的对象和结构体有什么区别?

发布于 2024-10-09 00:46:25 字数 118 浏览 0 评论 0原文

  • 对象与结构体有何区别?
  • 我们何时以及为何使用对象而不是结构体?
  • 数组与两者有何不同,何时以及为何使用数组而不是对象或结构?

我想了解每个的用途。

  • What distinguishes and object from a struct?
  • When and why do we use an object as opposed to a struct?
  • How does an array differ from both, and when and why would we use an array as opposed to an object or a struct?

I would like to get an idea of what each is intended for.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

南汐寒笙箫 2024-10-16 00:46:25

显然,您可以根据您的编程风格模糊这些区别,但通常结构是结构化的数据块。对象是可以执行某种任务的主权实体。在大多数系统中,对象具有某种状态,因此其背后有一些结构化数据。然而,设计良好的类的主要功能之一是数据隐藏——类究竟如何实现它所做的事情是不透明且无关紧要的。

由于类可用于表示经典数据结构,例如数组、哈希图、树等,因此您通常将它们视为结构化数据块中的单独事物。

数组是非结构化数据块。在许多编程语言中,数组中的每个单独的事物都必须具有相同的基本类型(例如每个都是整数、每个都是字符串或类似类型),但在许多其他语言中并非如此。

作为指导:

  • 使用数组作为放置一大组没有其他固有结构或层次结构的东西的地方,例如“一月份的所有收据”或“我在丹麦购买的所有东西”
  • 使用结构化数据来组合多个离散的数据位成一个块,例如您可能想要组合 x 位置和 y 位置来描述一个点,
  • 使用一个对象,其中有一个特定的参与者或事物为自己思考或行动

因此,对象的隐含目的是直接关联任务与他们可以操作的数据并将其捆绑在一起,以便系统的其他部分不会干扰。遵守正确的面向对象设计原则可能一开始需要遵守纪律,但最终会极大地改善您的代码结构,从而提高您处理更大项目和与他人合作的能力。

Obviously you can blur the distinctions according to your programming style, but generally a struct is a structured piece of data. An object is a sovereign entity that can perform some sort of task. In most systems, objects have some state and as a result have some structured data behind them. However, one of the primary functions of a well-designed class is data hiding — exactly how a class achieves whatever it does is opaque and irrelevant.

Since classes can be used to represent classic data structures such as arrays, hash maps, trees, etc, you often see them as the individual things within a block of structured data.

An array is a block of unstructured data. In many programming languages, every separate thing in an array must be of the same basic type (such as every one being an integer number, every one being a string, or similar) but that isn't true in many other languages.

As guidelines:

  • use an array as a place to put a large group of things with no other inherent structure or hierarchy, such as "all receipts from January" or "everything I bought in Denmark"
  • use structured data to compound several discrete bits of data into a single block, such as you might want to combine an x position and a y position to describe a point
  • use an object where there's a particular actor or thing that thinks or acts for itself

The implicit purpose of an object is therefore directly to associate tasks with the data on which they can operate and to bundle that all together so that no other part of the system can interfere. Obeying proper object-oriented design principles may require discipline at first but will ultimately massively improve your code structure and hence your ability to tackle larger projects and to work with others.

浅笑依然 2024-10-16 00:46:25

一般来说,对象带来了完整的面向对象的功能(方法、数据、虚函数、继承等),而结构只是有组织的内存。结构可能支持也可能不支持方法/函数,但它们通常不支持继承和其他完整的 OOP 功能。

请注意,我说的是一般来说...个别语言可以随意重载术语,但他们想这样做。

数组与 OO 无关。事实上,几乎所有语言都支持数组。数组只是内存块,通常包含一系列相似的项目,通常可以以某种方式进行索引。

Generally speaking, objects bring the full object oriented functionality (methods, data, virtual functions, inheritance, etc, etc) whereas structs are just organized memory. Structs may or may not have support for methods / functions, but they generally won't support inheritance and other full OOP features.

Note that I said generally speaking ... individual languages are free to overload terminology however they want to.

Arrays have nothing to do with OO. Indeed, pretty much every language around support arrays. Arrays are just blocks of memory, generally containing a series of similar items, usually indexable somehow.

素手挽清风 2024-10-16 00:46:25
  • 对象与结构体有何区别?

OOP 中没有“结构”的概念。结构的定义取决于所使用的语言。例如,在 C++ 中,类和结构是相同的,但默认情况下类成员是私有的,而结构成员是公共的,以保持与 C 结构的兼容性。另一方面,在 C# 中,struct 用于创建值类型,而 class 用于创建引用类型。 C 有结构体,但不是面向对象的。

  • 我们何时以及为何使用对象而不是结构体?

这又取决于所使用的语言。通常,结构用于表示 POD(普通旧数据),这意味着它们不指定作用于数据的行为,并且主要用于表示记录而不是对象。这只是一个约定,在 C++ 中并未强制执行。

  • 数组与两者有何不同,
    以及我们何时以及为什么要使用
    数组而不是对象或
    结构?

数组则非常不同。数组通常是由整数索引的同构元素集合。结构体是一个异构集合,其中的元素通过名称进行访问。您可以使用数组来表示相同类型的对象集合(例如颜色数组),而使用结构体来表示包含特定对象数据的记录(具有红色、绿色的单一颜色)和蓝色元素)

  • What distinguishes and object from a struct?

There is no notion of "struct" in OOP. The definition of structures depends on the language used. For example in C++ classes and structs are the same, but class members are private by defaults while struct members are public to maintain compatibility with C structs. In C# on the other hand, struct is used to create value types while class is for reference types. C has structs and is not object oriented.

  • When and why do we use an object as opposed to a struct?

Again this depends on the language used. Normally structures are used to represent PODs (Plain Old Data), meaning that they don't specify behavior that acts on the data and are mainly used to represent records and not objects. This is just a convention and is not enforced in C++.

  • How does an array differ from both,
    and when and why would we use an
    array as opposed to an object or a
    struct?

An array is very different. An array is normally a homogeneous collection of elements indexed by an integer. A struct is a heterogeneous collection where elements are accessed by name. You'd use an array to represent a collection of objects of the same type (an array of colors for example) while you'd use a struct to represent a record containing data for a certain object (a single color which has red, green, and blue elements)

远昼 2024-10-16 00:46:25

简短回答:结构是值类型。类(对象)是引用类型。

Short answer: Structs are value types. Classes(Objects) are reference types.

旧街凉风 2024-10-16 00:46:25

就其本质而言,对象具有方法,而结构则没有。

(没有什么可以阻止你拥有一个没有方法的对象,就像没有什么可以阻止你将整数存储在浮点类型变量中一样)

By their nature, an object has methods, a struct doesn't.

(nothing stops you from having an object without methods, jus as nothing stops you from, say, storing an integer in a float-typed variable)

妄断弥空 2024-10-16 00:46:25

我们何时以及为何使用对象而不是结构体?

这是一个关键问题。我使用结构和过程代码模块来提供 OOP 的大部分好处。结构提供对象的大部分数据存储功能(只读属性除外)。过程模块提供类似于对象提供的代码完成功能。我可以在 IDE 中输入 module.function 而不是 object.method。生成的代码看起来是一样的。我的大多数函数现在返回结构而不是单个值。这对我的代码的影响是巨大的,代码可读性提高了,行数也大大减少了。我不知道为什么广泛使用结构的过程编程并不常见。为什么不直接使用 OOP 呢?我使用的一些语言只是过程性的(PureBasic),并且使用结构可以体验 OOP 的一些好处。其他语言允许选择过程式或 OOP(VBA 和 Python)。我目前发现使用过程编程更容易,并且在我的学科(生态学)中,我发现定义对象非常困难。当我无法弄清楚如何将数据和函数组合成哲学上连贯的集合中的对象时,那么我就没有创建类/对象的基础。使用结构和函数,无需定义类的层次结构。我可以自由地在模块之间调整函数,这有助于我改进代码的组织。也许这是走向面向对象的前兆。

使用结构编写的代码比基于 OOP 的代码具有更高的性能。 OOP 代码具有封装性、继承性和多态性,但是我认为基于结构/函数的过程代码通常具有这些特征。函数仅向其调用者返回值并且仅在作用域内返回值,从而实现封装。同样,函数可以是多态的。例如,我可以编写一个函数,使用两种内部算法计算两个地点之间的时差,一种考虑国际日期变更线,另一种不考虑国际日期变更线。继承通常是指从基类继承的方法。调用其他函数并使用结构进行数据传输的函数存在某种继承。一个简单的例子是通过一堆嵌套函数传递错误消息。当错误消息向上传递时,可以通过调用函数将其添加到其中。结果是一个堆栈跟踪,其中包含非常具有描述性的错误消息。在这种情况下,消息通过多个级别继承。我不知道如何描述这种自下而上的继承(事件驱动编程?),但它是使用返回结构的函数的一个功能,而使用简单返回值的过程编程中则没有这种功能。目前我还没有遇到过 OOP 比函数和结构更有效率的情况。让我惊讶的是,互联网上可用的代码很少是这样编写的。这让我想知道这是否有什么原因?

When and why do we use an object as opposed to a struct?

This is a key question. I am using structs and procedural code modules to provide most of the benefits of OOP. Structs provide most of the data storage capability of objects (other than read only properties). Procedural modules provide code completion similar to that provided by objects. I can enter module.function in the IDE instead of object.method. The resulting code looks the same. Most of my functions now return stucts rather than single values. The effect on my code has been dramatic, with code readability going up and the number of lines being greatly reduced. I do not know why procedural programming that makes extensive use of structs is not more common. Why not just use OOP? Some of the languages that I use are only procedural (PureBasic) and the use of structs allows some of the benefits of OOP to be experienced. Others languages allow a choice of procedural or OOP (VBA and Python). I currently find it easier to use procedural programming and in my discipline (ecology) I find it very hard to define objects. When I can't figure out how to group data and functions together into objects in a philosophically coherent collection then I don't have a basis for creating classes/objects. With structs and functions, there is no need for defining a hierarchy of classes. I am free to shuffle functions between modules which helps me to improve the organisation of my code as I go. Perhaps this is a precursor to going OO.

Code written with structs has higher performance than OOP based code. OOP code has encapsulation, inheritance and polymorphism, however I think that struct/function based procedural code often shares these characteristics. A function returns a value only to its caller and only within scope, thereby achieving encapsulation. Likewise a function can be polymorphic. For example, I can write a function that calculates the time difference between two places with two internal algorithms, one that considers the international date line and one that does not. Inheritance usually refers to methods inheriting from a base class. There is inheritance of sorts with functions that call other functions and use structs for data transfer. A simple example is passing up an error message through a stack of nested functions. As the error message is passed up, it can be added to by the calling functions. The result is a stack trace with a very descriptive error message. In this case a message inherited through several levels. I don't know how to describe this bottom up inheritance, (event driven programming?) but it is a feature of using functions that return structs that is absent from procedural programming using simple return values. At this point in time I have not encountered any situations where OOP would be more productive than functions and structs. The surprising thing for me is that very little of the code available on the internet is written this way. It makes me wonder if there is any reason for this?

节枝 2024-10-16 00:46:25

数组是(通常)相同类型的项目的有序集合。可以通过索引访问项目。经典数组仅允许整数索引,但是现代语言通常提供所谓的关联数组(字典、散列等),允许使用例如字符串作为索引。

结构是命名值(字段)的集合,这些值可以是“不同类型”(例如,字段a存储整数值,字段b - 字符串值等)。它们(a)将逻辑连接的值组合在一起,(b)通过隐藏细节来简化代码更改(例如,更改结构布局不会影响使用该结构的函数的签名)。后者称为“封装”。

从理论上讲,对象是结构的一个实例,它展示了响应发送的消息的某些行为(即,在大多数语言中,具有某些方法)。因此,对象的真正有用之处在于这种行为,而不是它的领域。

不同的对象可以表现出不同的行为来响应相同的消息(调用相同的方法),这称为“多态性”。

在许多(但不是全部)语言中,对象属于某些类,并且类可以形成层次结构(称为“继承”)。

由于对象方法可以直接使用其字段,因此除此方法之外的任何代码都可以隐藏字段以防止其访问(例如,通过将它们标记为private)。因此,对象的封装级别可以高于结构的封装级别。

请注意,不同的语言为此术语添加了不同的语义。

例如:

  • 在 CLR 语言(C#、VB.NET 等)中,struct 在堆栈/寄存器中分配,对象在堆中创建。

  • 在 C++ 中,struct 默认情况下具有所有字段 public,而对象(类的实例)则具有所有字段 private

  • 在某些动态语言中,对象只是存储值和方法的关联数组。

Arrays are ordered collection of items that (usually) are of the same types. Items can be accessed by index. Classic arrays allow integer indices only, however modern languages often provide so called associative arrays (dictionaries, hashes etc.) that allow use e.g. strings as indices.

Structure is a collection of named values (fields) which may be of 'different types' (e.g. field a stores integer values, field b - string values etc.). They (a) group together logically connected values and (b) simplify code change by hiding details (e.g. changing structure layout don't affect signature of function working with this structure). The latter is called 'encapsulation'.

Theroretically, object is an instance of structure that demonstrates some behavior in response to messages being sent (i.e., in most languages, having some methods). Thus, the very usefullness of object is in this behavior, not its fields.

Different objects can demonstrate different behavior in response to the same messages (the same methods being called), which is called 'polymorphism'.

In many (but not all) languages objects belong to some classes and classes can form hierarchies (which is called 'inheritance').

Since object methods can work with its fields directly, fields can be hidden from access by any code except for this methods (e.g. by marking them as private). Thus encapsulation level for objects can be higher than for structs.

Note that different languages add different semantics to this terms.

E.g.:

  • in CLR languages (C#, VB.NET etc) structs are allocated on stack/in registers and objects are created in heap.

  • in C++ structs have all fields public by default, and objects (instances of classes) have all fields private.

  • in some dynamic languages objects are just associative arrays which store values and methods.

相思碎 2024-10-16 00:46:25

我还认为值得一提的是,结构体的概念与 Javascript 中的“对象”非常相似,它的定义与其他语言中的对象非常不同。它们都像“foo.bar”一样被引用,并且数据的结构类似。

I also think it's worth mentioning that the concept of a struct is very similar to an "object" in Javascript, which is defined very differently than objects in other languages. They are both referenced like "foo.bar" and the data is structured similarly.

痞味浪人 2024-10-16 00:46:25
  • 在我看来,基本级别的对象是许多变量和操作这些变量的许多方法,而另一方面,结构只是许多变量。
  • 当您想要包含方法时,我使用对象;当我只想传递变量集合时,我使用结构。
  • 数组和结构体在原理上有点相似,它们都是许多变量。然而,编写 myStruct.myVar 比编写 myArray[4] 更具可读性。您可以使用枚举来指定数组索引以获取 myArray[indexOfMyVar] 并基本上获得与结构相同的功能。

当然,您可以使用常量或其他东西来代替变量,我只是想展示基本原理。

  • As I see it an object at the basic level is a number of variables and a number of methods that manipulate those variables, while a struct on the other hand is only a number of variables.
  • I use an object when you want to include methods, I use a struct when I just want a collection of variables to pass around.
  • An array and a struct is kind of similar in principle, they're both a number of variables. Howoever it's more readable to write myStruct.myVar than myArray[4]. You could use an enum to specify the array indexes to get myArray[indexOfMyVar] and basically get the same functionality as a struct.

Of course you can use constants or something else instead of variables, I'm just trying to show the basic principles.

青芜 2024-10-16 00:46:25

这个答案可能需要更有经验的程序员的注意,但结构和对象之间的区别之一是结构没有反射能力,而对象可以。反射是对象报告其所具有的属性和方法的能力。这就是“对象资源管理器”如何查找并列出在用户定义的类中创建的新方法和属性。换句话说,反射可以用来计算出对象的接口。对于结构,据我所知,无法迭代结构的元素来找出它们的名称、类型和值。

如果使用结构体来替代对象,那么就可以使用函数来提供与方法等效的功能。至少在我的代码中,结构通常用于从包含业务逻辑的模块中的用户定义函数返回数据。结构体和函数与对象一样易于使用,但函数缺乏对 XML 注释的支持。这意味着我必须经常查看函数顶部的注释块才能了解该函数的作用。通常我必须阅读函数源代码才能了解如何处理边缘情况。当函数调用其他函数时,我经常不得不深入几个层次来追寻某些东西,并且很难弄清楚。这导致了 OOP 相对于结构和函数的另一个好处。 OOP 具有 XML 注释,这些注释在 IDE 中显示为工具提示(在大多数但不是所有 OOP 语言中),并且在 OOP 中还定义了接口,并且通常是对象图(如果您选择创建它们)。我越来越清楚,OOP 的决定性优势是能够记录代码的作用以及它与其他代码(接口)的关系。

This answer may need the attention of a more experienced programmer but one of the differences between structs and objects is that structs have no capability for reflection whereas objects may. Reflection is the ability of an object to report the properties and methods that it has. This is how 'object explorer' can find and list new methods and properties created in user defined classes. In other words, reflection can be used to work out the interface of an object. With a structure, there is no way that I know of to iterate through the elements of the structure to find out what they are called, what type they are and what their values are.

If one is using structs as a replacement for objects, then one can use functions to provide the equivalent of methods. At least in my code, structs are often used for returning data from user defined functions in modules which contain the business logic. Structs and functions are as easy to use as objects but functions lack support for XML comments. This means that I constantly have to look at the comment block at the top of the function to see just what the function does. Often I have to read the function source code to see how edge cases are handled. When functions call other functions, I often have to chase something several levels deep and it becomes hard to figure things out. This leads to another benefit of OOP vs structs and functions. OOP has XML comments which show up as tool tips in the IDE (in most but not all OOP languages) and in OOP there are also defined interfaces and often an object diagram (if you choose to make them). It is becoming clear to me that the defining advantage of OOP is the capability of documenting the what code does what and how it relates to other code - the interface.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文