如何使用成员初始化列表来初始化数组?

编程入门 行业动态 更新时间:2024-10-27 09:41:55
本文介绍了如何使用成员初始化列表来初始化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

A类{ public: A(); private: char a [5]; int * ptr; }; A :: A():a(0),ptr(0){}

这是正确的吗?

解决方案

03从它的C ++ 03标准中,§8.5/ 7:$ c

一个对象的初始值是一个空的圆括号,即(),应进行值初始化。

并从§8.5/ 5开始:

value-initialize 类型 T 的对象表示:

  • if T 是一个具有用户声明的构造函数的类类型,然后调用 T 的默认构造函数如果 T 没有可访问的默认构造函数,则是错误的);
  • 如果 T 是没有用户声明的构造函数的非联合类类型,那么 T 的每个非静态数据成员和基类组件都是值初始化的; li>
  • 如果 T 是数组类型,则每个元素都是值初始化的;
  • 否则,对象为零初始化

类型 T 的对象表示:

  • if T 是标量类型,对象设置为 0 (零)的值转换为 T ;
  • 如果 T 是非联合类类型,非静态数据成员和每个基类子对象都是零初始化的;
  • 如果 T 是联合类型,成员)是零初始化的;
  • 如果 T 是数组类型,每个元素都是零初始化的;
  • 如果 T 是引用类型,则不执行初始化。

所以,如果你的构造函数定义改为

A :: A ):a(),ptr(){}

的5个元素将具有值'\0'和 A的 :: ptr 将为null。

class A { public: A(); private: char a[5]; int* ptr; }; A::A() : a(0), ptr(0) { }

Is this right?

解决方案

The only sensible thing you can do with a C-array in C++03 is value-initialize it (in C++11 and beyond it can be list-initialized).

From the C++03 standard, §8.5/7:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

And from §8.5/5:

To value-initialize an object of type T means:

  • if T is a class type with a user-declared constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized

To zero-initialize an object of type T means:

  • if T is a scalar type, the object is set to the value of 0 (zero) converted to T;
  • if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
  • if T is a union type, the object’s first named data member) is zero-initialized;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.

So, if your constructor definition is changed to

A::A() : a(), ptr() { }

then you are guaranteed that post-construction, all 5 elements of A::a will have the value '\0' and A::ptr will be null.

更多推荐

如何使用成员初始化列表来初始化数组?

本文发布于:2023-07-30 11:06:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248838.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   数组   如何使用   成员   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!