对我不正当的术语道歉.
如果条目不存在,我有一段代码返回NULL指针:
ObjectType * MyClass::FindObjectType( const char * objectTypeName ) { if ( objectTypeMap.find( objectTypeName ) == objectTypeMap.end() ) { Msg( "\n[C++ ERROR] No object type: %s",objectTypeName ); return NULL; } else return &objectTypeMap[ objectTypeName ]; }
我想做同样的事情,但这次返回一个对象,而不只是一个指针.以下代码不会给我任何编译器错误(这让我感到惊讶):
ObjectType MyClass::FindObjectType( const char * objectTypeName ) { if ( objectTypeMap.find( objectTypeName ) == objectTypeMap.end() ) { Msg( "\n[C++ ERROR] No object type: %s",objectTypeName ); } else return objectTypeMap[ objectTypeName ]; }
用指针我可以检查是否没有找到这样的条目:
if ( FindObjectType( objectType ) == NULL ) //Do something
如何对待返回的对象执行等效检查?
解决方法@H_301_18@
对象没有语言层面的等价物.
一个选项是创建一个“哨兵”对象,保证与任何“真实”对象的不平等进行比较,并返回:
class ObjectType {
public:
static const ObjectType null;
bool operator==(const ObjectType &rhs) const { /* need an appropriate comparison test */ }
...
};
ObjectType ObjectType::null(/* something unique */);
...
ObjectType foo(const char *objectTypeName) {
if (cond) {
return objectTypeMap[objectTypeName];
} else {
return ObjectType::null;
}
}
...
if (foo(objectType) == ObjectType::null) {
std::cout << "Returned the null object\n";
}
一个选项是创建一个“哨兵”对象,保证与任何“真实”对象的不平等进行比较,并返回:
class ObjectType { public: static const ObjectType null; bool operator==(const ObjectType &rhs) const { /* need an appropriate comparison test */ } ... }; ObjectType ObjectType::null(/* something unique */); ... ObjectType foo(const char *objectTypeName) { if (cond) { return objectTypeMap[objectTypeName]; } else { return ObjectType::null; } } ... if (foo(objectType) == ObjectType::null) { std::cout << "Returned the null object\n"; }