私は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;
}
}
ゲームオブジェクト.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);
};
メッシュ.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);
}