如何使用dynamic_cast

Jef*_*ffR 2 c++ casting

我正在尝试使用dynamic_cast-没有成功。我有一个BASE类,以及一个从BASE派生的类A。我希望有一个指向BASE类对象的指针,该指针后来又要转换为A类。我显然没有正确执行此操作。以下代码编译:

#include <cstdio>

class BASE {
private:

    int i;

public:

     BASE(void) {i = 1; }
     virtual ~BASE(){}

     virtual void id() { printf("CLASS BASE\n"); }
 };

class A : public BASE {
public:
    A(void): BASE() {}
    A(const BASE & base) : BASE(base) {}
    A& operator = (const BASE & base) { static_cast<BASE&>(*this) = base; return *this; }

    void id() override { printf("CLASS A\n"); };
};


int main() {

    BASE* base = new BASE();

    base->id();

    A* a = new A(*base);

    a->id();

    A* anotherA = dynamic_cast<A*>(base);

    if(!anotherA) 
        printf("anotherA is NULL\n");
    else    
        anotherA->id();
}
Run Code Online (Sandbox Code Playgroud)

但是运行它可以得到:

CLASS BASE
CLASS A
anotherA is NULL
Run Code Online (Sandbox Code Playgroud)

我确定我缺少一些非常基本的东西,但是我一直盯着代码,看不到我在做什么错。任何帮助将不胜感激。

我看过

什么时候应该使用static_cast,dynamic_cast,const_cast和reinterpret_cast?

但是不明白为什么dynamic_cast不起作用-这不是一个简单的向下转换吗?

n. *_* m. 5

我确定我缺少一些非常基本的东西

你做。

当您有一个类型的对象A指向该类型的对象A*指针时,可以将指针转换为type BASE*。这种转换会部分忘记有关类型的信息。

现在给定类型的指针BASE*如果该指针实际上指向一个A对象(也就是说,它A*在某个点上是从类型转换的),则可以通过将指针转换回type 来调用被忘记的类型信息A*

如果您的指针未指向A开头的类型的对象,则不会遗忘任何内容,也没有可调用的内容。