基类指针可以指向一个派生类对象。为什么反之亦然不是真的? [英] A Base Class pointer can point to a derived class object. Why is the vice-versa not true?

查看:223
本文介绍了基类指针可以指向一个派生类对象。为什么反之亦然不是真的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基类指针可以指向派生类对象。为什么反之亦然不是真的没有铸造?
逻辑上,一个基类没有足够的派生类的信息,但派生类也应该有基类的信息。
我在这里缺少一些基础知识。

A Base Class pointer can point to a derived class object. Why is the vice-versa not true without casting? Logically a base class would not have enough information of the derived class but a derived class should have the information of the base class as well. I am missing some basics here.

推荐答案

如果我告诉你我有一只狗,我有一只狗。

If I tell you I have a dog, you can safely assume that I have a dog.

如果我告诉你我有一只宠物,你不知道那只动物是一只狗,它可能是一只猫,甚至可能是一只长颈鹿。不知道一些额外的信息,你不能安全地假设我有一条狗。

If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog.

同样,派生对象是一个基类对象(因为它是一个子类)可以通过基类指针指向。但是,一个基类对象不是一个派生类对象,所以它不能被赋给一个派生类指针。

similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.

(你现在听到的吱吱声是类比拉伸)

(The creaking you will now hear is the analogy stretching)

假设你现在想为我的宠物给我买礼物。

Suppose you now want to buy me a gift for my pet.

在第一种情况下,你知道它是一只狗,你可以给我一个皮带,每个人都很高兴。

In the first scenario you know it is a dog, you can buy me a leash, everyone is happy.

在第二种情况下,我没有告诉你我的宠物是什么,所以如果你要买我一个礼物,无论如何你需要知道的信息,我没有告诉你(或只是猜测),你买我一条皮带,如果事实证明我真的有一只狗,每个人都快乐。

In the second scenario I haven't told you what my pet is so if you are going to buy me a gift anyway you need to know information I haven't told you (or just guess), you buy me a leash, if it turns out I really did have a dog everyone is happy.

然而,如果我实际上有一只猫,那么我们现在知道你做了一个坏的假设(演员),并在一个皮带上有一个不快乐的猫(运行时错误)。

However if I actually had a cat then we now know you made a bad assumption (cast) and have an unhappy cat on a leash (runtime error).

这篇关于基类指针可以指向一个派生类对象。为什么反之亦然不是真的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆