How much functionality is “acceptable” for a C++ struct?

后端 未结 19 2364
礼貌的吻别
礼貌的吻别 2021-02-07 09:31

My first post so please go easy on me!

I know that there\'s no real difference between structs and classes in C++, but a lot of people including me use a struct or class

19条回答
  •  旧时难觅i
    2021-02-07 09:53

    The only methods I like to put on structs are property-type methods, simple transforms (and, if appropriate for the type, operators), and non-default constructors.

    Properties

    For instance, I might define a RECT struct as below:

    typedef struct tagRECT{
        int left;
        int top;
        int right;
        int bottom;
    
        int get_width(){return right - left;}
        int get_height(){return bottom - top;}
        int set_width(int width){right = left + width; return width;}
        int set_height(int height){bottom = top + height; return height;}
    } RECT, *PRECT;
    

    The "set" methods return the new value to support assignment chaining in the case that the compiler supports properties as an extension.

    Simple transforms

    For POD types that store complex data, I might include methods that perform simple transformations on that data. An obvious example might be including Rotate, Scale, Shear, and Translate methods on a TransformationMatrix struct.

    Operators

    Really just an extension of the above, if operators make sense for the type, I will add them to a struct. This can be appropriate and necessary to maintain the atomicity of the object. An obvious example is standard arithmetic operators on a Complex struct.

    Constructors

    I prefer not to have a default constructor on my structs. I don't want to allocate an array of PODs and suffer the invocation of a thousand (or whatever) default initializations. If memset initialization won't suffice, I'll provide an Initialize method.

    I will, however, provide a non-default constructor on structs. This is especially useful when one or more fields can be inferred from partial construction.

提交回复
热议问题