简体   繁体   中英

Struct inheritance causing non-aggregate type error on static initialization

I currently have the following:

struct MsgHeader_t
{
    int   a;
    float b;
};

which initializes a default const as

const MsgHeader_t default = { 0, 0.0f };

which was working fine. Now I have to extend it and it MUST inherit from another struct. So now I have.

struct MsgId_t
{
    unsigned int id;
};

struct MsgHeader_t : public MsgId_t
{
    int   a;
    float b;
};

But now when I try to initialize that default const ( const MsgHeader_t aMessage = { 0, 0, 0.0f }; ) I get

error: braces around initializer for non-aggregate type 'const MsgHeader_t'

Once you have inheritance, then your class can no longer be an aggregate type. From this Draft C++ Standard (bold italics mine):

8.5.1 Aggregates

1 An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

Note that since C++17, you might do, as you expect:

  • const MsgHeader_t aMessage = { 0, 0, 0.0f }; . Demo
  • or more properly const MsgHeader_t aMessage = { {0}, 0, 0.0f }; . Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM