Using typeid to get name of derived class

后端 未结 5 1858
孤城傲影
孤城傲影 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:50

    typeid of a pointer will always be the declared type, because that's the real type of the pointer itself. To know the real type of the object the pointer points to, you need to dereference the pointer to get the actual type: http://ideone.com/FYmp79

    #include 
    #include 
    using namespace std;
    
    struct Resource {
        virtual ~Resource() = default;
    };
    
    struct Texture : Resource {};
    
    int main() {
        Resource *resource = new Resource;
        Resource *texture = new Texture;
    
        cout << typeid(*resource).name() << endl; // yields 'Resource'
        cout << typeid(*texture).name() << endl; // yields 'Texture'
        return 0;
    }
    

    EDIT: as other people said, you need to make the class polymorphic to get the runtime type information.

提交回复
热议问题