static_cast/dynamic_cast:是否更改对象

static_cast/dynamic_cast: Does it change the object?

本文关键字:cast 对象 是否 dynamic static      更新时间:2023-10-16

我对C++中的static_castdynamic_cast有一些疑问。他们是否通过保留已经设置的成员变量(不能从派生传递到基的变量除外),将指针指向的对象从类A完全更改为类B

我注意到,如果我有类似的东西

struct Base
{
    Base() { }
    virtual ~Base() { }
    virtual void Method() { cout << "Base Method"; }
};
class Derived : public Base
{
public:
    virtual void Method() { cout << "Override Method"; }
};
struct Derived2 : public Derived
{
    Derived2() { cout << "Derived2 constructor"; }
    void Method() { cout << "Override2 Method"; }
};
int main()
{       
    Base *myPointer = new Derived();    
    static_cast<Derived2*>(myPointer)->Derived2::Method();   
    delete myPointer;    
    return 0;
}

构造函数没有被调用,但方法调用了。这怎么可能?

强制转换根本不会更改对象。它们只为您提供一个不同的指针,指向继承层次结构中的相关类类型:

Derived x;
Base         * p = &x;
AnotherClass * q = dynamic_cast<AnotherClass*>(p);
// q may or may not be NULL

例如,如果我们有一个层次结构AnotherClass : BaseDerived : AnotherClass(并且Base是多态的),那么上面的动态转换就会成功。

当您已经知道您有一个更派生的动态类型,但恰好只有一个指向基的指针或引用时,通常可以使用static_cast

(静态强制转换永远不能用于从虚拟基础进行强制转换,在这种情况下,总是需要dynamic_cast。)