What's the difference between an object and a struct in OOP?

后端 未结 10 1764
旧时难觅i
旧时难觅i 2021-01-30 09:05
  • 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 wh
10条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 09:26

    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.

提交回复
热议问题