Using typeid to get name of derived class

后端 未结 5 1743
孤城傲影
孤城傲影 2021-02-13 21:08

I\'m creating a resource manager that takes in classes derived from the class Resource. My problem is that typeid(..).name() returns the wrong name of the class.

5条回答
  •  遥遥无期
    2021-02-13 21:37

    If you are using Qt library, you could use the metaobject to distinguish the resource instances.

    class Resource : public QObject {
        Q_OBJECT
    
    }; // abstract
    
    class Texture : public Resource {
        Q_OBJECT
    };
    
    Resource *texture = new Texture();
    Resource *resource = new Resource();
    
    texture ->metaObject()->className(); // yields 'Texture'
    resource ->metaObject()->className(); // yields 'Resource'
    

提交回复
热议问题