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

后端 未结 19 2320
礼貌的吻别
礼貌的吻别 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条回答
  •  滥情空心
    2021-02-07 10:13

    I wasn't making a distinction between member and free functions when I was thinking about the question, but I now see that this was a mistake. It now seems to me that structs should only rarely have member functions. It is pretty clear that everything in a struct should be public.

    Therefore, there is generally no point in having struct member functions because any function can change the data in the struct. A member function on a struct would be a convenience rather than a necessity.

    The only exceptions would be things required to be member functions for some other purpose - constructors for initialising arrays; comparisons for use with a map; things used by templates; etc.

    Perhaps class and struct should be seen as opposites - a class exposes functions and hides data, whereas a struct exposes data and allows you to hide functions.

    Going back to the byte swapping example:

    struct S
    {
        int data;
        S() {data = 1234;}
        void ByteSwap() {network::ByteSwap( &data );}
    };
    
    S s;
    s.ByteSwap();
    

    would become:

    struct S
    {
        S() {data = 1234;}
        int data;
    };
    
    namespace network
    {
        void ByteSwap( int* i ) {/*byte swap *i*/}
        void ByteSwap( S* s ) {ByteSwap( &s->data );}
    
        S s;
        ByteSwap(&s);
    }
    

    This makes sense when the data and some functions do not always strongly belong together. Byte swapping would only be of interest to the network system but higher level functions can still use the struct without even knowing about low level stuff like byte swapping.

    Another benefit in this case is that the related byte swapping operations are all kept together in the same place.

提交回复
热议问题