对于一个简单的游戏,我有这个类,它检查游戏实体前面是否有任何对象。C++:分离标题和实现文件(.hpp/.cpp)时出现分段错误
class FieldOfView : public anax::System<FieldOfView>
{
public:
FieldOfView() :
Base(anax::ComponentFilter().requires<components::Transform, components::FieldOfView>())
{
}
void update()
{
using std::find;
using std::begin;
using std::end;
using std::remove_if;
auto& bus = Game::get().getMessageBus();
for (auto& entity : getEntities())
{
auto collisions = getCollisions(entity);
auto& inSight = entity.getComponent<components::FieldOfView>().inSight;
for (auto& collided : collisions)
{
if (find(begin(inSight), end(inSight), collided) == end(inSight))
{
inSight.push_back(collided);
bus.send<message::EntityEnteredFov>(entity, collided);
}
}
std::function<bool(const anax::Entity&)> hasCollided = [&collisions](const anax::Entity& x) -> bool {
return find(begin(collisions), end(collisions), x) != end(collisions);
};
for (const auto& seenEntity : inSight)
{
if (!hasCollided(seenEntity))
bus.send<message::EntityLeftFov>(entity, seenEntity);
}
inSight.erase(remove_if(begin(inSight), end(inSight), std::not1(hasCollided)), end(inSight));
}
}
};
该类位于文件“FieldOfView.hpp”中。它可以正常工作。不过,我想分开头文件和实现文件,所以我创建了一个“FieldOfView.cpp”。
void FieldOfView::update()
{
// the same code as above
}
我还更新了头文件( “FieldOfView.hpp”):因为段故障的
class FieldOfView : public anax::System<FieldOfView>
{
public:
FieldOfView() :
Base(anax::ComponentFilter().requires<components::Transform, components::FieldOfView>())
{
}
void update();
};
当该代码(HPP + CPP)运行时,该程序中止(Segmentation fault: 11
) 。在此行中出现的错误:
bus.send<message::EntityLeftFov>(entity, seenEntity);
当我编译和仅使用单一HPP(无CPP文件)一切正常运行的代码,不存在分段错误或任何其他类型的错误。我不知道是什么导致此行为...
猜测,你的代码在其他地方有问题。检查缓冲区溢出和内存使用情况 – 2014-10-19 11:21:23