簡體   English   中英

調用Function時未在此范圍內聲明數組

[英]Array not declared in this scope when call Function

我嘗試運行C ++程序時遇到一些問題。 它的作用是詢問用戶數組的大小以及數組的類型是double還是int,然后根據用戶的選擇,聲明該數組,然后調用一個用用戶值填充該數組的函數

#include <iostream>
using namespace std;

template<class T>
void fill(T *arr,int size){
        for(int i = 0; i < size; i ++){
                cout<<"Insert value " << i << " :" ;
                cin >> arr[i];
        }
}
int main(){
        int option,size;
        cout << "Size? ";
        cin >> size;
        cout << "1 = double" << endl
        << "2 = int" << endl;
        cin >> option;
        if(option == 1){
                double arr[size];
        }
        else if(option == 2){
                int arr[size];
        }
        fill(arr,size);
return 0;
}

但是當我嘗試運行它時,出現了此錯誤

test.cpp:在函數'int main()'中:test.cpp:24:7:錯誤:未在此范圍內聲明'arr'。fill(arr,size); ^

main() ,您的arr變量僅在聲明它們的if()塊的范圍內。 當達到if的close }時,它們將超出范圍。 因此,它們的確不在調用fill()范圍內。

無論如何,這並不重要,因為無論如何您都不能聲明具有多個類型的變量。 因此,您將無法在fill()的范圍內聲明單個arr數組變量,並且無法根據用戶輸入將數組類型設置為intdouble (當然,除非您使用std::variantstd::any ,但這是一個主題)。

您將需要在if()塊內調用fill() ,這些數組在作用域內。

另外,您還依賴於非標准的特定於供應商的擴展,稱為“可變長度數組”,也就是在自動(堆棧)內存而不是動態(堆)內存中分配可變大小的數組。 僅某些編譯器將該擴展實現為一項附加功能。 不要依賴它 分配可變大小數組的正確方法是改用new[]或更好的std::vector

嘗試更多類似這樣的方法:

#include <iostream>
#include <vector>

template<class T>
void fill(T *arr, int size){
    for(int i = 0; i < size; i ++){
        std::cout << "Insert value " << i << " :";
        std::cin >> arr[i];
    }
}

int main(){
    int option, size;

    std::cout << "Size? ";
    std::cin >> size;
    std::cout << "1 = double" << std::endl
              << "2 = int" << std::endl;
    std::cin >> option;

    if (option == 1) {
        std::vector<double> arr(size);
        fill(&arr[0], size);
    }
    else if (option == 2) {
        std::vector<int> arr(size);
        fill(&arr[0], size);
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM