具有继承层次结构的动态强制转换



所以我有这个代码:

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,我不太明白为什么。

提前谢谢。

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

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((函数适用于任何种类的动物,并且仅在动物实际上是狗的情况下才执行特定于狗的事情。

最新更新