我对 C++ 很陌生,所以我在学习时倾向于使用很多 Java 主义进行设计。无论如何,在 Java 中,如果我有一个带有“搜索”方法的类,它会T
从Collection< T >
与特定参数匹配的对象返回一个对象,我将返回该对象,如果在集合中找不到该对象,我将返回null
. 然后在我的调用函数中我会检查if(tResult != 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;
}
我怎样才能改变它,以便我可以给出那种标记?