Run-Time Checking of a Cast from a void*

前端 未结 3 1473
不思量自难忘°
不思量自难忘° 2021-01-19 12:21

Say that I have a void* containing a pointer to an unknown class. I want to use dynamic_cast to do run-time checking on the type of cl

3条回答
  •  一个人的身影
    2021-01-19 12:46

    To ensure dynamic_cast compiles and works, you should create an abstract or interface class with a virtual method.

    #include 
    
    class Bar
    {
    public:
        Bar() = default;
         virtual ~Bar() = default;
    };
    
    class Foo : public Bar
    {
    public:
        Foo() = default;
        virtual ~Foo() = default;
    };
    
    int main()
    {
        Bar* bar = new Foo;
        Foo* foo = dynamic_cast(bar);
        assert(foo != nullptr);
    }
    

提交回复
热议问题