Initializing a struct with aggregate initialization and member initializers [duplicate]

梦想的初衷 提交于 2019-12-03 10:19:31

Bjarne Stroustrup and Richard Smith raised an issue about aggregate initialization and member-initializers not working together.

The definition of aggregate is slightly changed in C++11 & C++14 standard.

From the C++11 standard draft n3337 section 8.5.1 says that:

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

But C++14 standard draft n3797 section 8.5.1 says that:

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).

So, when you use in class member initializer (i.e. equal initializer) for the data member id in C++11 it no longer remains aggregate & you can't write ABC abc{"hi", 0}; to initialize a struct ABC. Because it no longer remains aggregate type after that. But your code is valid in C++14. (See live demo here).

In c++ struct and classes are the same, except that structs have default public members and classes have private. If you want to use initial values I think you have to write a constructor or use something like this:

struct ABC
{
    std::string str;
    unsigned int id;
} ABC_default = {"init", 0 }; //initial values

int main()
{
    ABC abc = ABC_default;
    std::cout << abc.str << " " << abc.id << std::endl;
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!