c++ - 具有继承层次结构的动态转换
问题描述
所以我有这个代码:
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() 函数适用于任何种类的动物,并且仅当动物实际上是狗时才执行特定于狗的事情。
推荐阅读
- java - 无法通过 URL 下载 tomcat8 zip 文件,线程“main”java.net.UnknownHostException 中出现错误异常:downloads.apache.org
- java - 为什么 Kotlin 不能用可空值类型推断此 HashMap 的类型?
- python - 从两列表中替换一列中的值的 Pythonic 方式
- python - 谁在引用乔?用于析构函数/清理的 Pythonic 方法?
- javascript - 使用 lodash 从数组中获取具有相同值的分组数组
- python - 我将如何随机旋转和缩放从 pygame 中的类创建的每个精灵
- sql - 一次性使用随机数
- python - 如何识别 Firefox 当前是否正在使用 Python 播放 Youtube 视频?
- forms - 使用 Google reCAPTCHA v3 进行语义 UI / Fomantic UI 表单验证
- prometheus - 普罗米修斯:系列的掉落样本