返回“NULL”对象,如果没有找到搜索结果 [英] Return a "NULL" object if search result not found
问题描述
我是C ++的新手,所以我倾向于设计与许多Java-isms,而我在学习。无论如何,在Java中,如果我有一个'search'方法将从集合返回一个对象
匹配一个特定的参数,我会返回该对象,如果在集合中找不到该对象,我会返回 T
T> null
。然后在我的调用函数中,我只需检查 if(tResult!= null){...}
I'm pretty new to C++ so I tend to design with a lot of Java-isms while I'm learning. Anyway, in Java, if I had class with a 'search' method that would return an object T
from a Collection< T >
that matched a specific parameter, I would return that object and if the object was not found in the collection, I would return null
. Then in my calling function I would just check if(tResult != null) { ... }
C ++,我发现如果对象不存在,我不能返回 null
值。我只想返回一个类型T的指示符,通知调用函数没有找到任何对象。我不想抛出异常,因为它并不是一个特殊的情况。
In C++, I'm finding out that I can't return a null
value if the object doesn't exist. I just want to return an 'indicator' of type T that notifies the calling function that no object has been found. I don't want to throw an exception because it's not really an exceptional circumstance.
这是我的代码现在的样子:
This is what my code looks like right now:
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;
}
如何更改它以便我可以给这种标记? p>
How can I change it so I can give that kind of marker?
推荐答案
在C ++中,引用不能为null。如果你想要返回null如果没有找到,你需要返回一个指针,而不是一个引用:
In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
否则,如果你坚持通过引用返回,那么你应该抛出异常如果没有找到属性。
Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.
(顺便说一下,我有点担心你的方法 const $ c $因为哲学原因,我建议返回
const Attr *
。如果你也可以修改这个属性,你可以重载一个非 - const
方法返回一个非 - const
属性以及。)
(By the way, I'm a little worried about your method being const
and returning a non-const
attribute. For philosophical reasons, I'd suggest returning const Attr *
. If you also may want to modify this attribute, you can overload with a non-const
method returning a non-const
attribute as well.)
这篇关于返回“NULL”对象,如果没有找到搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!