C ++:struct / class中的构造方法对初始化器列表 [英] C++: Constructor versus initializer list in struct/class

查看:192
本文介绍了C ++:struct / class中的构造方法对初始化器列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用初始化程序列表创建结构/类(不包含构造函数)的对象。为什么不允许在具有构造函数的struct /类上?

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


推荐答案

构造函数不再被认为是POD(plain old data)。对象必须只包含其他POD类型作为非静态成员(包括基本类型)。 POD可以具有静态函数和静态复杂数据成员。

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.

请注意,即将到来的C ++标准将允许您定义初始化列表,这将允许非POD对象用大括号初始化。

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

这篇关于C ++:struct / class中的构造方法对初始化器列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆