How can I get the class name from a C++ object?

前端 未结 8 2148
名媛妹妹
名媛妹妹 2020-11-29 20:56

Is it possible to get the object name too?

#include

class one {
public:
    int no_of_students;
    one() { no_of_students = 0; }
    void new         


        
8条回答
  •  庸人自扰
    2020-11-29 21:36

    use typeid(class).name

    // illustratory code assuming all includes/namespaces etc

    #include 
    #include 
    using namespace std;
    
    struct A{};
    int main(){
       cout << typeid(A).name();
    }
    

    It is important to remember that this gives an implementation defined names.

    As far as I know, there is no way to get the name of the object at run time reliably e.g. 'A' in your code.

    EDIT 2:

    #include 
    #include 
    #include 
    using namespace std; 
    
    struct A{
    };
    struct B{
    };
    
    map m;
    
    int main(){
        m[&typeid(A)] = "A";         // Registration here
        m[&typeid(B)] = "B";         // Registration here
    
        A a;
        cout << m[&typeid(a)];
    }
    

提交回复
热议问题