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

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

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

25条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:04

    Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.

    If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.

    Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:

    template  struct type_traits {
      typedef T type;
      typedef T::iterator_type iterator_type;
      ...
    };
    

    ...But that's really just taking advantage of struct's default protection level being public...

提交回复
热议问题