![](/img/trans.png)
[英]Why do I get compile time error when base class pointer points to derived class virtual function that is declared in base class?
[英]Why do I get SIGSEGV error when use class function from pointer?
我是C ++的新手,遇到了第一次麻煩。 我有一個GameObject類,其中我必須以某種方式存儲許多組件。 每個組件都是一個不同的類,因此我通常不能使用vector。 我決定存儲組件的類型和指向該對象的指針。 問題是,當我得到該組件時,返回該組件,並使用一個使用其成員變量的類函數,則會收到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);
}
在這里
Mesh *mesh = new Mesh();
component.pointer = &mesh;
您正在獲取指向mesh
的指針的地址。 試一試
Mesh *mesh = new Mesh();
component.pointer = mesh;
因為您將Component
pointer定義為void* pointer
。 如果要獲取Mesh*
的地址,則必須使用void** pointer
,但這很愚蠢,並且會導致另一個SIGSEGV
。
if(components[i].type == MeshComponent)
{
return (Mesh*)&components[i].pointer;
}
您的返回類型為Mesh *,但&components[i].pointer
將為無效**。 + @ bas.d的上述解釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.