我是C++的新手,遇到了第一个麻烦。我有一个GameObject类,其中我必须以某种方式存储许多组件。每个组件都是不同的类,所以我不能只使用向量。我决定存储组件的类型和指向该对象的指针。问题是,当我得到,返回该组件,并使用使用它的成员变量的类函数时,我会得到SIGSEGV错误(是的,听起来很混乱)。但是,如果我通常使用那个类和那个函数,我就不会得到一个SIGSEGV错误。
GameObject.h:
enum ComponentType
{
MeshComponent // currently only one type
};
struct Component
{
ComponentType type;
void *pointer;
};
class GameObject
{
private:
std::vector<Component> components;
public:
void addComponent(ComponentType type);
template<typename T> T* getComponent()
{
for(std::vector<Component>::size_type i = 0; i != components.size(); i++)
{
// will need to somehow check T type later
if(components[i].type == MeshComponent)
{
return (Mesh*)&components[i].pointer;
}
}
Debug::Loge(GAMEOBJECT_TAG, "No %s component in %s gameobject!", componentTypeToString(MeshComponent).c_str(), name.c_str());
return 0;
}
}GameObject.cpp:
void GameObject::addComponent(ComponentType type)
{
Component component;
component.type = type;
if(type == MeshComponent)
{
Mesh *mesh = new Mesh();
component.pointer = &mesh;
}
components.push_back(component);
}Mesh.h
class Mesh
{
public:
Mesh *setMeshData(std::vector<GLfloat> data);
};Mesh.cpp
Mesh *Mesh::setMeshData(vector<GLfloat> data)
{
meshData = data;
return this;
}最后,我就是这样使用它的:
GameObject object;
void somefunction()
{
object.addComponent(MeshComponent);
object.getComponent<Mesh>()->setMeshData(triangle_data); // SIGSEGV HERE!!
// if I use this one instead above - no sigsegv, everything is fine.
Mesh mesh;
mesh.setMeshData(triangle_data);
}发布于 2013-08-20 08:18:17
在这里
Mesh *mesh = new Mesh();
component.pointer = &mesh;您正在获取指向mesh的指针的地址。相反,试着
Mesh *mesh = new Mesh();
component.pointer = mesh;因为您将Component-pointer定义为void* pointer。如果您想要获取Mesh*的地址,您必须使用void** pointer,但这是愚蠢的,并且会导致另一个SIGSEGV。
发布于 2013-08-20 10:36:36
if(components[i].type == MeshComponent)
{
return (Mesh*)&components[i].pointer;
}您的返回类型是Mesh*,但是&components[i].pointer将无效**。+ @bas.d的上述解释
https://stackoverflow.com/questions/18330105
复制相似问题