我是 C + + 的新手,所以在学习的时候,我倾向于使用大量的 Java 语言进行设计。无论如何,在 Java 中,如果我有一个带有“ search”方法的类,它将从 Collection< T >返回一个匹配特定参数的对象 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;
}
我怎样才能改变它,这样我就可以给那种记号笔?