When should you use a class vs a struct in C++?

后端 未结 25 1652
误落风尘
误落风尘 2020-11-22 00:18

In what scenarios is it better to use a struct vs a class in C++?

25条回答
  •  迷失自我
    2020-11-22 00:45

    One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.

    typedef struct
    {
        int messageId;
        int messageCounter;
        int messageData;
    } tMessageType;
    
    void processMessage(unsigned char *rawMessage)
    {
        tMessageType *messageFields = (tMessageType *)rawMessage;
        printf("MessageId is %d\n", messageFields->messageId);
    }
    

    Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.

提交回复
热议问题