简体   繁体   English

如何使用 dynamic_cast

[英]How to use dynamic_cast

I am trying to use dynamic_cast - with no success.我正在尝试使用 dynamic_cast - 没有成功。 I have a BASE class, and a class A derived from BASE.我有一个 BASE 类和一个从 BASE 派生的 A 类。 I want to have a pointer to a BASE class object which I later want to cast to class A. I clearly am not doing this correctly.我想要一个指向 BASE 类对象的指针,稍后我想将其转换为 A 类。我显然没有正确执行此操作。 The following code compiles:以下代码编译:

#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();
}

but running it gives:但运行它会给出:

CLASS BASE
CLASS A
anotherA is NULL

I am sure I'm missing something very basic, but I keep staring at the code and can't see what I'm doing wrong.我确定我遗漏了一些非常基本的东西,但我一直盯着代码看,看不出我做错了什么。 Any help would be very much appreciated.任何帮助将不胜感激。

I have looked at我看过

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? 什么时候应该使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?

but don't understand why dynamic_cast doesn't work - isn't this just a simple downcast?但不明白为什么 dynamic_cast 不起作用 - 这不是一个简单的向下转换吗?

I am sure I'm missing something very basic我确定我错过了一些非常基本的东西

You do.你做。

When you have an object of type A , and a pointer to that object of type A* , the pointer can be converted to type BASE* .当您有一个A类型的对象和一个指向A*类型对象的指针时,该指针可以转换为BASE*类型。 This conversion partially forgets information about the type.这种转换部分地忘记了有关类型的信息。

Now given a pointer of type BASE* , if this pointer actually points to an A object (that is, it was converted from type A* at some point), you can recall forgotten type information by casting the pointer back to type A* .现在给定一个BASE*类型的指针,如果这个指针实际上指向一个A对象(也就是说,它在某个时候从A*类型转换而来),您可以通过将指针转换回A*类型来回忆忘记的类型信息。

If your pointer does not point to an object of type A to begin with, then nothing was forgotten and there is nothing to recall.如果您的指针开始时没有指向类型为A的对象,那么什么都没有忘记,也没有什么可回忆的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM