2013-08-20 63 views
1

我是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); 
} 
+0

'return(Mesh *)&components [i] .pointer;'快速瀏覽 - 看起來您正在獲取想要的指針('.pointer'),然後將地址*指針*並返回。 – BoBTFish

+0

你應該至少檢查一下''object.getComponent ()''不返回''0''。 – juanchopanza

+0

std :: vector >可能會讓生活更輕鬆,如果你有C++ 11 – doctorlove

回答

2

在這裏

Mesh *mesh = new Mesh(); 
    component.pointer = &mesh; 

你正在服用的指針的地址mesh。相反,嘗試

Mesh *mesh = new Mesh(); 
    component.pointer = mesh; 

,因爲你定義你的Component終場前爲void* pointer。如果你想採取Mesh*的地址,你將不得不使用void** pointer,但這是愚蠢的,並會導致另一個SIGSEGV

+1

還有'return(Mesh *)&components [i] .pointer'這是同一類問題。 – Nbr44

0
if(components[i].type == MeshComponent) 
{ 
    return (Mesh*)&components[i].pointer; 
} 

您的返回類型是Mesh *,但&components[i].pointer將爲void **。 + @ bas.d的上述解釋

相關問題