我對C++很新穎,所以我傾向於在學習時用很多Java-ims進行設計。無論如何,在Java中,如果我有一個'搜索'方法的類將返回匹配一個特定參數的Collection< T >
對象T
,我會返回該對象,如果在該集合中找不到對象,我會返回null
。然後在我的調用函數,我只是檢查if(tResult != null) { ... }
如果搜索結果未找到,則返回「NULL」對象
在C++中,我發現如果對象不存在,我不能返回null
值。我只想返回一個類型爲T的「指示符」,通知調用函數沒有找到對象。我不想拋出異常,因爲這不是一個真正的例外情況。
這是我的代碼看起來像現在:
class Node {
Attr& getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return attributes[i];
//if not found
return NULL; // what should this be?
}
private:
vector<Attr> attributes;
}
我怎樣才能改變它,所以我可以給那種標記?
異常和NULL並不總是唯一的解決方案。你經常可以選擇一個返回值來表示找不到:例如,如果沒有元素匹配,'std :: find(first,last,value)'返回'last'。 – Cascabel 2010-04-14 16:47:39