首页 > 解决方案 > 具有继承层次结构的动态转换

问题描述

所以我有这个代码:

Base* objbase = new Derived();

//perform a downcast at runtime with dynamic_cast
Derived* objDer = dynamic_cast<Derived*>(objBase);

if(objDer)//check for success of the cast
    objDer->CallDerivedFunction();

这是我书中的演员阵容部分的代码片段。

现在为什么我有这个,我不明白必须动态转换指向指向派生对象的基础对象的指针有什么意义;对我来说,这与多态性使我们有能力做有关objBase->DeriveClassFunction(),但我真的不知道。

首先它为什么这样做:Base* objbase = new Derived();,然后为什么又将基对象指针转换为 Derived,我不太明白为什么。

提前致谢。

标签: c++casting

解决方案


该代码片段只是对可能性的演示。它描述了一个工具,你用这个工具做什么取决于你。一个稍微大一点的例子可能是:

class Animal {
    void Feed();
};
class Cat : public Animal { /*...*/ };
class Dog : public Animal {
    // Only dogs need to go out for a walk
    void WalkTheDog();
};

void Noon(Animal* pet)
{
    // No matter what our pet is, we should feed it
    pet->Feed();

    // If our pet is a dog, we should also take it out at noon
    Dog* dog = dynamic_cast<Dog*>(pet);
    if(dog) // Check if the cast succeeded
        dog->WalkTheDog();
}

Noon(new Cat()); // Feed the cat
Noon(new Dog()); // Feed the dog and take him out

请注意,每个动物都有 Feed() 函数,但只有狗有 WalkTheDog() 函数,所以为了调用该函数,我们需要有一个指向狗的指针。但是为这两种类型复制 Noon() 函数也是相当浪费的,特别是如果我们以后可能会添加更多的动物。因此,Noon() 函数适用于任何种类的动物,并且仅当动物实际上是狗时才执行特定于狗的事情。


推荐阅读