in C++, can I derive a class from a struct

后端 未结 3 2011
一整个雨季
一整个雨季 2020-12-09 15:36

The question says it all really. Am I allowed derive a class from a struct, or should I create a class that embeds my struct and defines copy constructors and an = operator

3条回答
  •  醉梦人生
    2020-12-09 16:08

    Yes. you can derive a class from a struct. In C++, a struct is simply a class where the default access is public rather than private. Deriving a class from a struct that only adds non-virual member functions and/or static functions is a useful technique to provide a C++ interface while maintaining compatability with a C style API.

    This is exactly the approach used by MFC for many of the C structs (contrary to what you state in your question).

    For example, the CRect class is publicly derived from struct tagRECT (the more commonly used name RECT is a typededf for struct tagRECT). Because struct tagRECT defines all the data members, and CRect adds only non-virtual member functions, the memory layout of CRects and RECTs are identical - you can use a CRect as an argument for any function expected a RECT and vice-versa.

提交回复
热议问题