search

Home  >  Q&A  >  body text

c++ - A question about static_cast

The static_cast operator converts expression to type-id type, but there is no runtime type check to ensure the safety of the conversion.
① Used to convert pointers or references between base classes (parent classes) and derived classes (subclasses) in the class hierarchy.
It is safe to perform upstream conversion (convert a pointer or reference of a derived class into a base class representation);
When performing downconversion (convert a pointer or reference from a base class to a derived class representation), because there is no Dynamic type checking, so it is unsafe.

From: http://baike.baidu.com/link?u...

I would like to ask, what does the bold part mean? What does unsafe mean?

阿神阿神2753 days ago856

reply all(1)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-05 11:13:51

    For example, there is a parent class A, which derives two subclasses B and C. There is a A class pointer or reference a pointing to a Bclass object b. In this case, use static_cast performs downward conversion and can convert it into an object (pointer or reference) of class C. At this time, it will be unsafe because some member functions/variables of class C are not compatible with objects of class B Be applicable.
    Simply put, you can use static_cast to convert objects of different subclasses of the same parent class to each other, resulting in type errors.
    For example:

    class A {
    public:
        void function_A();
    };
    class B:public A {
    public:
        void function_B();
    };
    class C:public A {
    public:
        void function_C();
    };
    
    int main() {
        A* a;
        B b;
        a = &b;
        C* c = static_cast<C*>(a);  //cast合法
        c->function_C();            //此处会调用不存在的函数,
                                    //实际上c指向的是一个B类的对象
                                    //但是此处强行将其作为C类的对象解释
        return 0;
    }

    reply
    0
  • Cancelreply