我对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