我是C++新手,遇到了第一個麻煩。我有一個GameObject類,我必須以某種方式存儲許多組件。每個組件都是不同的類,所以我不能正常使用vector。我決定存儲一個組件的類型和指向該對象的指針。問題是,當我得到時,返回該組件,並使用一個使用它的成員變量的類函數,我得到SIGSEGV錯誤(是的,聽起來令人困惑)。但是,如果我通常使用該類和該函數,則不會收到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);
}
'return(Mesh *)&components [i] .pointer;'快速瀏覽 - 看起來您正在獲取想要的指針('.pointer'),然後將地址*指針*並返回。 – BoBTFish
你應該至少檢查一下''object.getComponent()''不返回''0''。 –
juanchopanza
std :: vector>可能會讓生活更輕鬆,如果你有C++ 11 –
doctorlove