activate RTTI in c++

后端 未结 7 1779
日久生厌
日久生厌 2020-12-09 14:37

Can anybody tell me how to activate RTTI in c++ when working on unix. I heard that it can be disabled and enabled. on my unix environment,how could i check whether RTTI is e

7条回答
  •  -上瘾入骨i
    2020-12-09 15:33

    Enabling and disabling RTTI must be a compiler specific setting. In order for the dynamic_cast<> operation, the typeid operator or exceptions to work in C++, RTTI must be enabled. If you can get the following code compiled, then you already have RTTI enabled (which most compilers including g++ do automatically):

    #include 
    #include 
    
    class A
    {
    public:
      virtual ~A () { }
    };
    
    class B : public A
    {
    };
    
    void rtti_test (A& a)
    {
      try
        {
          B& b = dynamic_cast (a);
        } 
      catch (std::bad_cast)
        {
          std::cout << "Invalid cast.\n";
        }
      std::cout << "rtti is enabled in this compiler.\n";
    }
    
    int
    main ()
    {
      A *a1 = new B;
      rtti_test (*a1);  //valid cast
      A *a2 = new A;
      rtti_test (*a2);  //invalid cast
      return 0;
    }
    

提交回复
热议问题