c++ - A question about static_cast
阿神
阿神 2017-06-05 11:11:51
0
1
837

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?

阿神
阿神

闭关修行中......

reply all(1)
仅有的幸福

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template