![](/img/trans.png)
[英]Why would I even use istream::ignore when checking for valid input?
[英]Should I use exceptions for checking valid input?
我正在使用gcc10.2
, c++20
。
在 python 學習 2 年后,我正在學習 c++。
在 python 中,我們總是對輸入有效性進行運行時檢查
def createRectangle(x, y, width, height): # just for example
for v in [x, y, width, height]:
if v < 0:
raise ValueError("Cant be negative")
# blahblahblah
我將如何在 c++ 中執行此過程?
for (int v : {x, y, width, height})
if (v < 0)
throw std::runtime_error("Can't be negative");
請注意,這樣的循環將每個變量復制兩次。 如果您的變量復制繁重(例如容器),請改用指針:
for (const int *v : {&x, &y, &width, &height})
if (*v < 0)
...
評論還建議使用參考,例如for (const int &v: {x, y, width, height})
,但這仍然會為每個變量提供一份副本。 所以如果一個類型那么重,我更喜歡指針。
在 C++ 中:
使用適當的類型,以便驗證(此時您使用變量而不是從某些輸入設置它們)是不必要的,例如對於長度unsigned
。 C++ 的類型比 Python 的類型更強,因此您不需要大量的驗證檢查來確保將正確的類型傳遞給 function。
throw
大致相當於 Python 中的raise
。 在 C++ 中,我們傾向於從std::exception
派生異常,然后拋出該異常。
Boost ( www.boost.org ) 有一個很好的驗證庫,值得一看。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.