Possible Duplicate:
C++ return a “NULL” object if search result not found
我正在尝试在特定条件下返回NULL,但它不允许我这样做,为什么不这样做?如何使它返回null值或0?
struct Entity
{
USHORT X;
USHORT Y;
UINT Serial;
USHORT SpriteID;
EntityType Type;
Direction FacingDirection;
};
函数是:
Entity& GetEntityAt(int index)
{
if (!GameObjects.empty())
{
lock_guard<mutex> lock(PadLock);
Entity& result = GameObjects[index];
return result;
}
return NULL; // <- this won't compile
}
最佳答案
C ++中没有空引用之类的东西。您的选择包括:
更改函数以返回(智能)指针。
创建一个虚拟的哨兵对象(const Entity null_entity
),并返回对该对象的引用。