Usage preference between a struct and a class in D language

前端 未结 2 1820
名媛妹妹
名媛妹妹 2021-01-17 07:25

When should I define a type as a struct or as a class?

I know that struct are value types while classes are reference types. So I wonder, for example, should I defin

2条回答
  •  旧时难觅i
    2021-01-17 07:47

    Read "D"iving Into the D Programming Language

    In D you get structs and then you get classes. They share many amenities but have different charters: structs are value types, whereas classes are meant for dynamic polymorphism and are accessed solely by reference. That way confusions, slicing-related bugs, and comments à la // No! Do NOT inherit! do not exist. When you design a type, you decide upfront whether it'll be a monomorphic value or a polymorphic reference. C++ famously allows defining ambiguous-gender types, but their use is rare, error-prone, and objectionable enough to warrant simply avoiding them by design.

    For your Stack type, you are probably best off defining an interface first and then implementations thereof (using class) so that you don't tie-in a particular implementation of your Stack type to its interface.

提交回复
热议问题