C ++如何在类似初始化器的列表中将指针数组设置为null? [英] C++ How do you set an array of pointers to null in an initialiser list like way?

查看:1221
本文介绍了C ++如何在类似初始化器的列表中将指针数组设置为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您不能将初始化列表用于数组.但是,我听说过可以将指针数组设置为NULL的方式,该方式类似于初始化程序列表.

I am aware you cannot use an initialiser list for an array. However I have heard of ways that you can set an array of pointers to NULL in a way that is similar to an initialiser list.

我不确定这是怎么做到的.我听说默认情况下将指针设置为NULL,尽管我不知道在C ++标准中是否可以保证.我也不确定与常规分配相比,通过new运算符进行初始化是否也会有所作为.

I am not certain how this is done. I have heard that a pointer is set to NULL by default, though I do not know if this is guaranteed/ in the C++ standard. I am also not sure if initialising through the new operator compared to normal allocation can make a difference too.

我的意思是在头文件/构造函数初始化列表中执行此操作.我不想将其放在构造函数中,也不想使用Vector.

I mean to do this in a header file/constructor initialisation list. I do not want to put it in the constructor, and I do not want to use a Vector.

推荐答案

要在构造函数初始值设定项列表中将指针数组设置为null,可以使用()初始值设定项

In order to set an array of pointers to nulls in constructor initializer list, you can use the () initializer

struct S {
  int *a[100];

  S() : a() {
    // `a` contains null pointers 
  }
};

不幸的是,在当前语言版本中,()初始值设定项是唯一可以与构造函数初始值设定项列表中的数组成员一起使用的初始值设定项.但这显然是您所需要的.

Unfortunately, in the current version of the language the () initializer is the only initializer that you can use with an array member in the constructor initializer list. But apparently this is what you need in your case.

()对用new[]

int **a = new int*[100]();
// `a[i]` contains null pointers 

在其他情况下,您可以使用{}聚合初始化程序实现相同的效果

In other contexts you can use the {} aggregate initializer to achieve the same effect

int *a[100] = {};
// `a` contains null pointers 

请注意,绝对不需要在{}之间挤压0NULL.空的{}对就可以了.

Note that there's absolutely no need to squeeze a 0 or a NULL between the {}. The empty pair of {} will do just fine.

这篇关于C ++如何在类似初始化器的列表中将指针数组设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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