Constans由函數分配的變量,用於創建數組C ++

[英]Constans variable assigned by function and used to create array C++


I use Visual Studio 2012

我使用Visual Studio 2012

My target:

User give array size -> function return data to const variable -> and create array. It is possible?

用戶給出數組大小 - >函數返回數據到const變量 - >並創建數組。有可能的?

Here is my code snippets:

這是我的代碼片段:

const int user_get_array_size()
{
int a;
bool blokada;

do
{
    cout << "Podaj wielkość tablicy: ";
    cin >> a;

    //Jeśli cin nie mógł zapisać danych do inta.
    //Lub wielkość tablicy mniejsza od 1? (Po co nam analizować coś co ma )
    if(cin.fail() || a < 2)
    {
        blokada = true;


        //Czyszczenie Cina z syfów.
        //Cin wchodzi char by char
        //while(cin)
        //{
            cin.clear(); //Czyszczenie CINA
        //}

        cin.ignore();

        system("CLS");
        cout << "Wielkość tablicy musi być liczą wiekszą od 1 \n(Wkońcu ten program ma coś analizować.) \n";
    }
    else
    {
        blokada = false;
    }
}
while(blokada);



return a;
}


const int w_array = user_get_array_size();

int tablica[ w_array ];

I got error : Expression must have constant value?

我得到錯誤:表達式必須具有恆定值?

Where is my fault?

我的錯在哪里?

1 个解决方案

#1


2  

If you initialize const int w_array like the following:

如果你初始化const int w_array如下:

const int w_array = 100;

Then there would be no problem as 100 is known at compile time. However, you initialize w_array with the return from the function which is only known at run time. Therefore, you cannot use w_array in the array declaration because the value needs to be known at compile time.

然后就沒有問題,因為在編譯時已知100。但是,您使用函數的返回初始化w_array,該函數僅在運行時已知。因此,您不能在數組聲明中使用w_array,因為需要在編譯時知道該值。

The easiest way to fix your code is to use std::vector:

修復代碼的最簡單方法是使用std :: vector:

std::vector<int> tablica(w_array);

Note that const is tricky in C++. When you initialize it with a literal, it can be used in contexts that require constant expressions. When you initialize it with a value only known at run time, it is a read-only variable but it cannot be used in contexts that require constant expressions.

請注意,const在C ++中很棘手。使用文字初始化時,可以在需要常量表達式的上下文中使用它。使用僅在運行時已知的值初始化它時,它是一個只讀變量,但不能在需要常量表達式的上下文中使用。

Also, some of the problems have been solved with constexpr functions in C++11. However, visual studio does not support this yet, and since your code requires input from the user, you would not be able to use it anyway.

此外,使用C ++ 11中的constexpr函數解決了一些問題。但是,visual studio還不支持此功能,並且由於您的代碼需要用戶輸入,因此無論如何都無法使用它。


注意!

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



 
粤ICP备14056181号  © 2014-2021 ITdaan.com