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

后端 未结 10 1763
旧时难觅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:31
    • 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.

    0 讨论(0)
  • 2021-01-30 09:34

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

    0 讨论(0)
  • 2021-01-30 09:39

    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.

    0 讨论(0)
  • 2021-01-30 09:43
    • 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)

    0 讨论(0)
提交回复
热议问题