Const数组初始化如果太长

[英]Const array initialization if its too long


In my answer to this question it was mentioned that the code I posted wouldn't work if the variable was declared as const.

在我对这个问题的回答中提到,如果变量被声明为const,我发布的代码将无效。

What if i want to initialize a long array that's const type

如果我想初始化一个const类型的长数组怎么办?

int main (){
    const int ar[100];
 //this is invalid in c++
 //something like this

    for (int i=0;i <100;++i)
        ar[i]=i;
    return 0;
}

Are there other ways to do this than using the #define method proposed in that question?

还有其他方法可以使用该问题中提出的#define方法吗?

2 个解决方案

#1


2  

There's no way to do it directly, without hacks.

没有黑客,没有办法直接做到这一点。

In C++ one way to work around this problem is to take advantage of the fact that inside their constructors const objects are still modifiable. So, you can wrap your array into a class and initialize it in the constructor

在C ++中,解决这个问题的一种方法是利用它们的构造函数const对象内部仍然可以修改的事实。因此,您可以将数组包装到类中并在构造函数中初始化它

struct Arr 
{
  int a[100];

  A() 
  {
    for (unsigned i = 0; i < 100; ++i)
      a[i] = i;
  }
};

and then just declare

然后宣布

const Arr arr;

Of course, now you will have to access it as arr.a[i], unless you override the operators in Arr.

当然,现在你必须以arr.a [i]的身份访问它,除非你覆盖Arr中的运算符。

#2


1  

You could use a trick... initialize a regular array and then get a reference to a const array:

您可以使用技巧...初始化常规数组,然后获取对const数组的引用:

int arr[100];
for (int i=0; i<100; i++) arr[i] = i*i;

const int (&carr)[100] = arr;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/06/10/30f01a72ea1b5d0b409e41abaa2b14bc.html



 
  © 2014-2022 ITdaan.com 联系我们: