在构造函数初始化器中初始化成员数组 [英] Initializing a member array in constructor initializer

查看:686
本文介绍了在构造函数初始化器中初始化成员数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class C 
{
public:
 C() : arr({1,2,3}) //doesn't compile
{}
    /*
    C() : arr{1,2,3} //doesn't compile either
{}
    */
private:
 int arr[3];
};

我相信原因是数组只能用 = 语法,即:

I believe the reason is that arrays can be initialized only with = syntax, that is:

int arr[3] = {1,3,4};



问题



Questions


  1. 我如何做我想做的(
    是在
    构造函数中的初始化数组,而不是在body中分配元素
    )。是甚么可能?

  2. C ++ 03标准在ctor初始化器中初始化聚合(包括数组)有什么特别的吗?或者上述代码的无效是一些其他规则的推论?

  3. Do C ++ 0x初始值列表是否解决了这个问题?

  1. How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible?
  2. Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?
  3. Do C++0x initializer lists solve the problem?

> PS 请不要提及向量,boost ::数组,以及它们对数组的优势,我非常清楚。

P.S. Please do not mention vectors, boost::arrays, and their superiority to arrays, which I am well aware of.

推荐答案



  1. 我如何做我想做的(即,在构造函数中初始化一个数组)。是甚么可能?


是的。它使用包含数组的结构。你说你已经知道了,但后来我不明白这个问题。这样,您就可以在构造函数中初始化数组,而不在body中分配。这是 boost :: array 的用法。

Yes. It's using a struct that contains an array. You say you already know about that, but then I don't understand the question. That way, you do initialize an array in the constructor, without assignments in the body. This is what boost::array does.


C ++ 03标准在ctor初始化器中初始化聚合(包括数组)有什么特别的吗?或者上述代码的无效是一些其他规则的推论?

Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?

mem初始化程序使用直接初始化。第8条的规则禁止这种事。我不确定下面的情况,但一些编译器允许它。

A mem-initializer uses direct initialization. And the rules of clause 8 forbid this kind of thing. I'm not exactly sure about the following case, but some compilers do allow it.

struct A {
  char foo[6];
  A():foo("hello") { } /* valid? */
};

请参阅此GCC PR 了解更多详情。

See this GCC PR for further details.


Do C ++ 0x初始值列表解决了这个问题?

Do C++0x initializer lists solve the problem?

是的,他们做。但是你的语法是无效的,我想。您必须直接使用大括号来启动列表初始化

Yes, they do. However your syntax is invalid, I think. You have to use braces directly to fire off list initialization

struct A {
  int foo[3];
  A():foo{1, 2, 3} { }
  A():foo({1, 2, 3}) { } /* invalid */
};

这篇关于在构造函数初始化器中初始化成员数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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