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 联系我们: