Creating a new object from dynamic type info

前端 未结 8 988
南旧
南旧 2020-12-05 05:22

In C++, is there any way to query the type of an object and then use that information to dynamically create a new object of the same type?

For example, say I have a

8条回答
  •  时光取名叫无心
    2020-12-05 05:51

    In C++, is there any way to query the type of an object...

    Yes, use typeid() operator

    For example:

    // typeid, polymorphic class
     #include 
     #include 
     #include 
     using namespace std;
    
     class CBase { virtual void f(){} };
     class CDerived : public CBase {};
    
     int main () {
       try {
         CBase* a = new CBase;
         CBase* b = new CDerived;
          cout << "a is: " << typeid(a).name() << '\n';
         cout << "b is: " << typeid(b).name() << '\n';
         cout << "*a is: " << typeid(*a).name() << '\n';
         cout << "*b is: " << typeid(*b).name() << '\n';
        } catch (exception& e) { cout << "Exception: " << e.what() << endl; }
        return 0;
      }
    

    Output:

    a is: class CBase *
    b is: class CBase *
    *a is: class CBase
    *b is: class CDerived
    

    If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception

    Read more.....

提交回复
热议问题