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

前端 未结 8 2124
名媛妹妹
名媛妹妹 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:35

    Just write simple template:

    template<typename T>
    const char* getClassName(T) {
      return typeid(T).name();
    }
    
    struct A {} a;
    
    void main() {
       std::cout << getClassName(a);
    }
    
    0 讨论(0)
  • 2020-11-29 21:36

    use typeid(class).name

    // illustratory code assuming all includes/namespaces etc

    #include <iostream>
    #include <typeinfo>
    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 <typeinfo>
    #include <iostream>
    #include <map>
    using namespace std; 
    
    struct A{
    };
    struct B{
    };
    
    map<const type_info*, string> m;
    
    int main(){
        m[&typeid(A)] = "A";         // Registration here
        m[&typeid(B)] = "B";         // Registration here
    
        A a;
        cout << m[&typeid(a)];
    }
    
    0 讨论(0)
提交回复
热议问题