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

后端 未结 10 1760
旧时难觅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: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)

提交回复
热议问题