我对 C++ 还很陌生,所以在学习时我倾向于使用大量 Java 主义进行设计。无论如何,在 Java 中,如果我有一个带有“搜索”方法的类,它将返回一个对象T
from a 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;
}
我怎样才能改变它以便我可以给出那种标记?
在 C++ 中,引用不能为空。如果您想在未找到任何内容时选择返回 null,则需要返回一个指针,而不是引用:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
否则,如果您坚持通过引用返回,那么如果未找到该属性,您应该抛出异常。
(顺便说一句,我有点担心你的方法是const
并返回一个非const
属性。出于哲学原因,我建议返回const Attr *
。如果您还想修改此属性,则可以使用非重载const
方法返回一个非const
属性也是如此。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)