2017-08-06 123 views
0

我有一個函數生成一個安全的輸入與錯誤處理,所以它是乾淨的輸入數字(INT)。但我希望其中一個參數是一個長度爲2的可選數組,其中包含所需變量輸入的邊界。如何將特定大小的數組作爲參數傳遞?

下面是我對現在:

//function prototype 
void input_number(int* variable, string text = "Input : ", int boundaries[2] = NULL); 

//function call 
int variable; 
input_number(&variable, "Choose a number between 0 and 10 : ", {0, 10}); 

這不起作用,引發錯誤cannot convert '<brace-enclosed initializer list>' to 'int*' for argument '3' to 'void input_number(int*, std::__cxx11::string, int*)'

如何傳遞長度爲2的數組的功能?

另外,是int[] = NULL正確的默認數組值或我是完全錯誤的?

回答

2

錯誤消息解釋該問題 - 當作爲參數傳遞給函數的陣列被轉換爲指針(到第一個元素)。

一種解決方案是通過一個有兩個成員的struct類型,並給出一個默認值。一個例子是,由於std::array實際上是一個模板結構

void input_number(int* variable, std::string text = "Input : ", const std::array<int, 2> &bounds = {}); 

int variable; 
input_number(&variable, "Choose a number between 0 and 10 : ", {0, 10}); 

然而,可以存儲兩個值,並且使用initializer_list<int>由任何數據結構。標準庫中還有其他類型的例子 - std::array不是唯一的例子。

就個人而言,我還省略了第一個參數,並將其作爲返回值

int input_number(std::string text = "Input : ", const std::array<int, 2> &bounds = {}); 

// to call 

int variable = input_number("Choose a number between 0 and 10 : ", {0, 10}); 

這不是拋出一個異常已經不能夠報告錯誤(其他功能的問題),但你的方法也是如此。

就我個人而言,我也不會將邊界作爲默認參數傳遞。我只是簡單地使用函數重載來做到這一點。

int input_number(std::string input, int lower_bound, int upper_bound) 
{ 
    // do whatever you want 
} 

int input_number(std::string input) 
{ 
     return input_number(input, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); 
} 

迫使呼叫者要麼提供無參數之後的第一個(在這種情況下,默認界限被使用),或兩個(其指定邊界) - 只通過一個附加參數將是可診斷的誤差。與你所問的唯一區別是,這不需要(隱式或顯式地)構造一個數組或其他數據結構來調用函數 - 這對於調用者來說更容易處理。

+0

感謝您的詳細解答!很多額外的建議,我喜歡它。是的,即使我想避免函數重載,我想我絕對沒有別的選擇使用它們! – lolgab123

+0

剛剛閱讀,用你剛剛寫道,重載沒有比沒有超載更多的空間..非常好的解決方案謝謝! (+在最後一個代碼塊中有一個額外的閉括號,在輸入之後,可能會被刪除) – lolgab123

2

嘗試這種情況:

void input_number(int* variable, string text = "Input : ", std::array<int, 2> boundaries = {}); 
+0

把這個數組作爲const&也可能是一個好的建議,但是在這一點上它是首選:只是打開了幾個用例。 – TheKitchenSink

+0

在這種情況下不獲益@TheKitchenSink。根據錯誤消息,Asker看起來在呼叫中使用了「{}」。 – user4581301

+0

不幸的{}並不意味着「沒有數組」,它意味着「數組填充0」。 –

相關問題