C++: Constructor versus initializer list in struct/class

送分小仙女□ 提交于 2019-12-30 08:15:27

问题


An object of a struct/class (that has no constructor) can be created using an initializer list. Why is this not allowed on struct/class with constructor?

struct r { int a; };
struct s { int a; s() : a(0) {} };
r = { 1 }; // works
s = { 1 }; // does not work

回答1:


No, an object with a constructor is no longer considered a POD (plain old data). Objects must only contain other POD types as non-static members (including basic types). A POD can have static functions and static complex data members.

Note that the upcoming C++ standard will allow you to define initializer lists, which will allow non-POD objects to be initialized with braces.




回答2:


If by your question you mean to ask, "Can I do this:"

struct MyGizmo
{
  char things_[5];
  MyGizmo() : things_({'a', 'b', 'c', 'd', 'e'}) ();
};

...then the answer is no. C++ doesn't allow this.



来源:https://stackoverflow.com/questions/2095759/c-constructor-versus-initializer-list-in-struct-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!